2017-03-07 64 views
0

我想編寫一個函數,它接受一個字符串,然後使用該名稱輸出class屬性的值。在實踐中,會有不止一種財產選擇形式。例如...使用字符串參數來描述類的屬性

class Apple{ 
    var juiciness : Int = 0 
    init(juiciness: Int){ 
    self.juiciness = juiciness 
    } 
} 

var myApple(juiciness : 10) 

func printValue(property : String){ 
    print(Apple.property) // <-- I want to use the string to choose a property 
} 

很顯然,我不能做到這一點的代碼,但我知道必須有不只是我一系列的if語句更好的解決方案。

+0

http://stackoverflow.com/questions/24138705/access-properties-via:

let label = UILabel() print(label.value(forKey: "font")) 

自己的類可以通過NSObject的繼承支持志願-subscripting-in-swift – chengsam

+0

你真的*想要一個字符串嗎?這將更好地實施封閉。 – Hamish

+0

爲了將來的參考,這種功能被稱爲「反射」 – Alexander

回答

1

蘋果已經爲你做了這個。它被稱爲鍵值觀察(KVO)。 試試下面的代碼在操場:

class YourClass: NSObject{ ... } 
+0

作爲NSManagedObject,我可以從NSObject繼承嗎? – spogatetz

+1

@spogatetz NSManagedObject是NSObject的一個子類。你可以簡單地從NSManagedObject繼承。 – LinShiwei

+0

這很有道理,謝謝。 – spogatetz