2016-06-07 89 views
0

計劃使用字符串值來引用要更新的對象,但不確定如何完成此操作。組合來自幾個不同的用戶選擇的來源的字符串。使用if/case語句的許多可能性。看下面的代碼,[ref]是我想要使用字符串的地方。提前致謝。swift,使用字符串引用對象名稱

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
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" 
... 

相關問題