我想編寫一個函數,它接受一個字符串,然後使用該名稱輸出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語句更好的解決方案。
http://stackoverflow.com/questions/24138705/access-properties-via:
自己的類可以通過NSObject的繼承支持志願-subscripting-in-swift – chengsam
你真的*想要一個字符串嗎?這將更好地實施封閉。 – Hamish
爲了將來的參考,這種功能被稱爲「反射」 – Alexander