gpt4 book ai didi

string - Swift,使用字符串名称来引用变量

转载 作者:搜寻专家 更新时间:2023-11-01 05:48:46 29 4
gpt4 key购买 nike

计划使用字符串值来引用我要更新的变量。组合来自几个不同用户选择源的字符串。使用 if/case 语句的多种可能性。提前致谢

var d1000: Int = 0
// ...
var d1289: Int = 0
// ...
var d1999: Int = 0

var deviceIDtype: Character = "d" // button press assigns some value, d used for example
var deviceIDsection: String = "12" // button press assigns some value, 12 used for example
var deviceID: String = "89" // button press assigns some value, 89 used for example

var ref:String = ""

func devName(dIDt:Character, dIDs: String, dID: String) -> String {
var combine: String = String(dIDt) + (dIDs) + (dID)
return (combine)
}

ref = devName(deviceIDtype, dIDs: deviceIDsection, dID: deviceID) // ref equals d1289 in this example


// d1289 = 1234 // trying to set this using the ref variable value, failed attempts below
/(ref) = 1234 // set d1289 variable to equal "1234"
"/(ref)" = 1234 // set d1289 variable to equal "1234"
get(ref) = 1234 // set d1289 variable to equal "1234"
get.ref = 1234 // set d1289 variable to equal "1234"

最佳答案

这是可能的!!!

let index = 1000
if let d1000 = self.value(forKey: "d\(index)") as? Int {
// enjoy
}

关于string - Swift,使用字符串名称来引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647476/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com