我想编写一个函数,它接受一个字符串,然后使用该名称输出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