【发布时间】:2017-03-07 02:23:53
【问题描述】:
我想编写一个函数,它接受一个字符串,然后打印具有该名称的类属性的值。在实践中,会有不止一种属性可供选择。比如……
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 语句更好的解决方案。
【问题讨论】:
-
你真的要拿一个字符串吗?使用闭包会更好地实现。
-
为了将来参考,这种功能称为“反射”
-
不需要是字符串。我将如何使用闭包来做到这一点?
标签: swift class parameters