Create a variable in swift with dynamic name

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].

Leave a Comment