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

Get the value of a Swift variable from a constructed name

我遇到了一个问题,我想在 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 下的变量名获取值。

使用数组

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

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

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)
    }
}

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