从构造名称获取Swift变量的值

时间:2017-08-28 21:34:02

标签: swift variables reflection swift4

我遇到了一个我想在Swift 4中弄清楚的问题。

假设我有以下变量

let var1 = "One"
let var2 = "Two"
let var3 = "Three"

var counter = 1

// Loop Start

let currentVariable = "var" + "\(counter)"

//Fetch the value of variable stored under currentVariable

counter += 1

//Loop end

我正在尝试根据currentVariable下的变量名称获取值。

2 个答案:

答案 0 :(得分:1)

您可以设置字典,用键替换变量名。

let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var myDictionary:[String:String] = ["var1":"One", "var2":"Two", "varA":"A", "varB":"B"]  // note, both sides can be different types than String

for x in 0...9 {
    let myKey = "var" + String(x)
    printValue(myKey)
}
for x in letters.characters {
    let myKey = "var" + String(x)
    printValue(myKey)
}

简单的功能:

func printValue(_ key:String) {
    let myValue = myDictionary[key]
    if myValue != nil {
        print(myValue)
    }
}

我很确定你可以让事情变得更优雅,但你明白了。另外,请记住,词典是"无序",而不是数组。

答案 1 :(得分:0)

使用数组

let myArray = ["one", "two", "three"];
var counter = 1;
print(myArray[counter]);