skip to Main Content

I have a program that is trying to list my classes for school (in a UITableView), along with the homework for each class. I have variables to track homework for each class as lists (i.e "Englishhw", "Mathhw", etc.), and I want to make it so that in my function, I can take the name of the class, and add "hw" to find the associated variable list. I have all of my homework lists for each class in one View Controller, and based on what the person selected (with the didSelectRowAt function, I can find that), I would show different table view contents for the homework in that class (instead of making a separate view controller for each subject). Here is my code:

    @IBOutlet var className: UILabel!
    var classList = ["Language", "Math", "English"]
    var Languagehw = ["hi", "bye", "New Assignment . . .", "Remove Assignment . . ."]
    var Mathhw = ["him", "bye", "New Assignment . . .", "Remove Assignment . . ."]
    var Englishhw = ["hime", "bye", "New Assignment . . .", "Remove Assignment . . ."]



   func addAssignment(subject: String) {
        for subject in classList {
            if className.text! == subject { 
                 // subject + hw to find associated variable (ex. subject = English, subject + hw => Englishhw, which is one of my homework lists
            }
            else {}
        }
    }

In this code, I’m making a function that checks if the className is equal to a subject in classList (a list with all of the classes) through a for loop and then trying to find the related list by adding the subject + hw. For example, if I wanted to find my "Englishhw" list, I could use the function to find if the class they selected was "English", and then add "hw" at the end to find the list correctly. However, I don’t know if there is a way to concatenate strings (in this case, English and hw) to find a variable. Is there actually concatenate strings into variables?

2

Answers


  1. Inside your for loop, you can write it as-

    if className.text! == subject + "hw" { 
          // here subject + "hw" is Englishhw now.
    }
    

    We can easily concate string as-
    after the given string mystring + "hw"
    before given string "hw" + mystring

    Login or Signup to reply.
  2. Forget concatenation; it’s irrelevant.

    What you need to know is that Swift has no introspection. There is no way to get from the string "Language" to the value of the variable Language (or Languagehw or anything else); that is a metaphysical impossibility.

    You need to rethink your entire architecture (which is pretty bad already: you should be using objects, not arrays). If you need to access a particular value by way of a string, that would be a dictionary with string keys.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search