我想编写一个接受字符串的函数,然后使用该名称打印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 :(得分:1)
let label = UILabel()
print(label.value(forKey: "font"))
您自己的类可以通过继承NSObject来支持KVO:
class YourClass: NSObject{ ... }