Create a variable in swift with dynamic name

前端 未结 4 963
闹比i
闹比i 2020-12-03 21:34

In swift, in a loop managed by an index value that iterates, I want to create a variable which has the variable name that is a concatenation of \"person_\" and the current l

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 22:11

    One solution is to store all your variables in an array. The indexes for the variables you store in that array will correspond to the index values you're trying to include in the variable name.

    Create an instance variable at the top of your view controller:

    var people = [WhateverTypePersonIs]()

    Then create a loop that will store however many people you want in that instance variable:

    for var i = 0; i < someVariable; i++ {
        let person = // someValue of type WhateverTypePersonIs
        people.append(person)
    }
    

    If you ever need to get what would have been "person_2" with the way you were trying to solve your problem, for example, you could access that person using people[2].

提交回复
热议问题