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

时间:2016-06-05 22:38:46

标签: string swift variables dictionary

计划使用字符串值来引用我想要更新的变量。组合来自几个不同用户选择的来源的字符串。有很多可能使用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"

2 个答案:

答案 0 :(得分:4)

如何使用字典[String : Int]

这将允许您实现您想要的 - 存储不同键的值。

例如,而不是使用

var d1000 = 0
var d1289 = 0
var d1999 = 0

您可以使用

var dictionary: [String : Int] = [
  "d1000" : 0,
  "d1289" : 0,
  "d1999" : 0
]

要在字典中存储值,只需使用

dictionary[key] = value
//for example, setting "d1289" to 1234
dictionary["d1289"] = 1234

要从字典中获取值,请使用

let value = dictionary[key]
//for example, getting the value of "d1289"
let value = dictionary["d1289"]

所以,你可以使用这样的东西

//initialize your dictionary
var myDictionary: [String : Int] = [:]

//your key initialization data
var deviceIDtype: Character = "d"
var deviceIDsection: String = "12"
var deviceID: String = "89"
var ref: String = ""

//your code
func devName(/*...*/){/*...*/}
ref = devName(/*...*/)

//set the key ref (fetched from devName) to 1234
myDictionary[ref] = 1234

正如旁注,你可以真正清理你的一些代码

func devName(type: Character, section: String, id: String) -> String{      
    return String(type) + section + id
}

//...

let key = devName(deviceIDtype, section: deviceIDsection, id: deviceID)
let value = 1234
myDictionary[key] = value

答案 1 :(得分:4)

有可能!!!

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