Mahmut Mahmut - 7 months ago 8
Swift Question

How get value from variables of similar names

Sequential variable names defined. I want to reach a variable relative to the corresponding value.

var code = 2 // 5, 6, ... // corresponding values
var name : String

var name1 : String = "Aaaaaa"
var name2 : String = "Bbbbbb"
// var name3
// var name4 ...

name = "name" + String(code) // name = "Bbbbb" ??


I do not get the results I wanted.
I hope i explained correctly. Thank you for your help.

Answer

Unlike in Objective-C, you can't access a variable by a String of its name in Swift. In your case, you might want to just use an array:

var code = 2 // 5, 6, ... // corresponding values
var names = ["Aaaaaa", "Bbbbbb"]
var name = names[code - 1] // "Bbbbbb"

If you really want to do it, you'll have to bridge to Objective-C, for example:

class SomeObject: NSObject {
    var name1 : String = "Aaaaaa"
    var name2 : String = "Bbbbbb"

    func getName(code: Int) -> String {
        let name = valueForKey("name" + String(code)) as! String  // "Bbbbbb"
        return name
    }
}

SomeObject().getName(2) // "Bbbbbb"

Of course, by doing this, you lose a lot of the safety that Swift provides.