【问题标题】:Using a string parameter to describe class property使用字符串参数来描述类属性
【发布时间】: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


【解决方案1】:

Apple 已经为您完成了这项工作。它被称为键值观察(KVO)。 在 Playground 中尝试以下代码:

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

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

class YourClass: NSObject{ ... }

【讨论】:

  • 我可以从 NSObject 作为 NSManagedObject 继承吗?
  • @spogatetz NSManagedObject 是 NSObject 的子类。您可以简单地从 NSManagedObject 继承。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2017-10-05
相关资源
最近更新 更多