2014-12-13 32 views
7

是否可以使用變量作爲Swift中的方法或屬性的名稱來訪問方法或屬性?如何從變量訪問屬性或方法?

在PHP中,您可以使用$ object - > {$ variable}。例如

class Object { 
    public $first_name; 
} 

$object = new Object(); 
$object->first_name = 'John Doe'; 

$variable = 'first_name'; 
$first_name = $object->{$variable}; // Here we can encapsulate the variable in {} to get the value first_name 
print($first_name); 
// Outputs "John Doe" 

編輯:

下面是實際的代碼,我的工作:

class Punchlist { 
    var nid: String? 
    var title: String? 

    init(nid: String) { 

     let (result, err) = SD.executeQuery("SELECT * FROM punchlists WHERE nid = \(nid)") 
     if err != nil { 
      println("Error") 
     } 
     else { 
      let keys = self.getKeys() // Get a list of all the class properties (in this case only returns array containing "nid" and "title") 
      for row in result { // Loop through each row of the query 
       for field in keys { // Loop through each property ("nid" and "title") 
        // field = "nid" or "title" 
        if let value: String = row[field]?.asString() { 
         // value = value pulled from column "nid" or "title" for this row 
         self.field = value //<---!! Error: 'Punchlist' does not have a member named 'field' 
        } 
       } 
      } 
     } 
    } 

    // Returns array of all class properties 
    func getKeys() -> Array<String> { 
     let mirror = reflect(self) 
     var keys = [String]() 
     for i in 0..<mirror.count { 
      let (name,_) = mirror[i] 
      keys.append(name) 
     } 

     return keys 
    } 
} 

回答

7

你可以這樣做,但不使用 「純」 斯威夫特。整個Swift(作爲語言)的一點是阻止那種危險的動態屬性訪問。你不得不使用Cocoa的Key-Value Coding功能:

self.setValue(value, forKey:field) 

非常方便,而且它穿過正是要穿越字符串到屬性名稱的橋樑,但要注意:這裏是龍。

(但它會更好,如果可能的話,重新實現你的架構作爲一本字典。字典是任意的字符串鍵和相應的值,因此沒有橋跨越。)

+0

這就是我在尋找和試圖做之前張貼在這裏。但是,我忘了將NSObject擴展到我的類,因此沒有得到.setValue()選項。我在這篇文章之前也在考慮@ bluedome的回答,但是,我在這堂課中有大約30個屬性,並且正在尋找避免下標中硬編碼的方法。 – balatin 2014-12-22 19:52:38

+0

+1作爲字典建議的實現體系結構。非常好的問題是要問自己,這是純數據問題還是真的需要跨越動態語言線 – bitwit 2016-01-06 17:03:42

8

下標可以幫助你。

let punch = Punchlist() 
punch["nid"] = "123" 
println(punch["nid"]) 

class Punchlist { 
    var nid: String? 
    var title: String? 

    subscript(key: String) -> String? { 
     get { 
      if key == "nid" { 
       return nid 
      } else if key == "title" { 
       return title 
      } 
      return nil 
     } 
     set { 
      if key == "nid" { 
       nid = newValue 
      } else if key == "title" { 
       title = newValue   
      } 
     } 
    } 
}