Create a variable in swift with a dynamic name

In a fast, loop controlled by the index value that iterates over, I want to create a variable that has the name of the variable, which is a concatenation of "person_" and the current index of the loop.

So my loop ends up creating variables like:

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

I was not lucky to find on the Internet, so post here.

Thanks!

+6
source share
4 answers

One solution is to store all your variables in an array. The indexes for the variables that you store in this array will correspond to the indexes you want 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 as many people as you like in this 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 "person_2" would be with how you tried to solve your problem, for example, you can access this person using people[2] .

+3
source

let name = "person _ \ (index)"

then add the name to the mutable array declared before the loop.

Something like that?

+1
source

What you are trying to do is not possible in the fast. The variable name is intended only for the person (especially in a compiled language), which means that they are devoid of the compilation phase.

BUT, if you really really want to do this, the code generation tool is the way to go. Find a suitable code generation tool, run it in the build phase.

0
source

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

Create an Array and populate it with user data. Later you can access individuals through your 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" 
0
source

Source: https://habr.com/ru/post/980346/


All Articles