swift,使用字符串引用对象名称

时间:2016-06-07 01:51:42

标签: string swift object reference

计划使用字符串值来引用我想要更新的对象,但不确定如何完成此操作。组合来自几个不同用户选择的来源的字符串。有很多可能使用if / case语句。看下面的代码,[ref]是我试图使用字符串的地方。提前谢谢。

class Equipment {
        var eType: String = "default"
        var name: String = "default"
        var a: Double = 1
        var b: Double = 0
        // ...
        var z: Int = 0

        init(eType: String, name: String){self.eType = eType; self.name = name
        }
    }
    var d1010 = Equipment(eType: "Panel X", name: "L1 Panel X")
    // ...
    var d1289 = Equipment(eType: "Panel X", name: "L2 Panel 39")
    // ...
    var d1999 = Equipment(eType: "Panel X", name: "L2 Panel 99")

    var deviceIDtype: Character = "d" // some input value from button press
    var deviceIDsection: String = "12" // some input value from button press
    var deviceID: String = "89" // some input value from button press

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

    let ref = devName(deviceIDtype, dIDs: deviceIDsection, dID: deviceID)
    // ref = d1289

    // d1289.etype = "some value"
    // d1289.name = ...
    // need something below to work like above using ref to get values to right object
    [ref].etype = "some val"
    [ref].name = "some val"
    [ref].a = 1.1
    [ref].b = 2.2
    // ...
    [ref].z = 24

1 个答案:

答案 0 :(得分:1)

var equipments: [String: Equipment] = [:]
equipments["d1010"] = Equipment(eType: "Panel X", name: "L1 Panel X")
equipments["d1289"] = Equipment(eType: "Panel X", name: "L2 Panel 39")
equipments["d1999"] = Equipment(eType: "Panel X", name: "L2 Panel 99")

...

equipments[ref]?.etype = "some value"
equipments[ref]?.name = "name"
...