Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a variable in swift with dynamic name

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 loop index.

So my loop ends up creating variables like:

var person_0 = ...
var person_1 = ...
var person_2 = ...
etc...

I had no luck searching online so am posting here.

Thanks!

like image 732
Greg Avatar asked Dec 31 '14 06:12

Greg


People also ask

Can you dynamically create variables?

Use an Array of Variables The simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.


2 Answers

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

like image 162
trevorj Avatar answered Oct 01 '22 10:10

trevorj


In Swift it is not possible to create dynamic variable names. What you are trying to achieve is the typical use case for an Array.

Create an Array and fill it with your person data. Later, you can access the persons via its index:

var persons: [String] = []

// fill the array
for i in 0..<10 {
    persons.append("Person \(i)")
}

// access person with index 3 (indexes start with 0 so this is the 4th person)
println(persons[3])  // prints "Person 3"
like image 39
zisoft Avatar answered Oct 01 '22 10:10

zisoft