使用字符串参数来描述类属性

时间:2017-03-07 02:23:53

标签: swift class parameters

我想编写一个接受字符串的函数,然后使用该名称打印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语句。

1 个答案:

答案 0 :(得分:1)

Apple已为您完成此操作。它被称为键值观测(KVO)。 在操场上尝试以下代码:

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

您自己的类可以通过继承NSObject来支持KVO:

class YourClass: NSObject{ ... }