swift获取名称存储在另一个变量中的类属性

时间:2017-07-21 18:39:40

标签: swift properties

如果我有一个带有我的类属性的数组“属性”

public class Circle {
  private var properties = ["radius", "diameter", "area", "perimeter"]

  public var radius: Double = 0.0
  public var diameter: Double = 0.0
  public var area: Double = 0.0
  public var perimeter: Double = 0.0

有没有办法使用数组获取属性的值??

我试过了:

    public var description: String {
      var str = description()
      for label in properties {
          let value = label
          str +=  label + "\t\(self.(value))\n"
    }
    return str
}

但它不起作用,如何使用存储在另一个变量(如“value”)中的名称来获取属性?

1 个答案:

答案 0 :(得分:1)

如果您可以更新类以符合NSObject,则可以使用valueForKey:方法

public class Circle: NSObject {
  private var properties = ["radius", "diameter", "area", "perimeter"]

  public var radius: Double = 0.0
  public var diameter: Double = 0.0
  public var area: Double = 0.0
  public var perimeter: Double = 0.0

  public var description: String {
    var str = description()
    for label in properties {
        let value = value(forKey: label)
        str +=  label + "\t\(label): \(value)\n"
  }
  return str
}