dynamic name for variables swift

is it possible to have a dynamic variable in swift. What i want to do is have a chuck of code which writes a variable: I.E


var number = 0


var person+\(number) = "on"


can you help


thanks

No.

Why not just use an array?

There isn't a way to dynamically create variables in Swift.


I think a Dictionary would usually be used in that situation, with a generated string "person \(number)" being the key used to set and retrieve the value.

Or, if your numbers will always be a range 0..<count, in an Array as Jens suggested.

is it possible to programatically create thousands of varibles: E.G person1, person2, person3, etc

Everyone above already answered, "No, just use an array or a dictionary."

Even Objective-C wasn't able to do that.

You can really do this "Super Directly"

But for a property in a class (or struct even in Swift), you can use @selector, to fetch the VALUE of the property, using a String, if you use Setters/Getters...

But no you can't really CREATE a variable with on the fly, but as others have said USE A DICTIONARY!

For instance

var myOnTheFlyHeap: [String : Any] = [ : ], or [String : Any?]

and just throw something in!

myOnTheFlyHeap["person1"] = "Johnny Appleseed"

Laters...

dynamic name for variables swift
 
 
Q