Can I set values for a Swift object properties using mirroring?

时间:2015-09-30 23:11:50

标签: json swift swift2 mirror mirroring

Right now I can inspect variables of an object using Mirror type. But can I set values for my variables using mirroring? Or maybe there's another pure-Swift way?

For example, I'd like to create an object (a Swift struct) from JSON. Is it possible without subclassing NSObject and using Objective-C functions for that?

2 个答案:

答案 0 :(得分:2)

这是我目前能做的最好的事情。它仍然缺少将mirrorObject转换回其泛型类型。仅供参考,这是使用SwiftyJSON

func convertToObject<T>(json: JSON, genericObject: T) -> T {
    let mirroredObject = Mirror(reflecting: genericObject)

    for (_, var attr) in mirroredObject.children.enumerate() {
        if let propertyName = attr.label as String! {
            attr.value = json[propertyName]
            print(propertyName)
            print(attr.value)
        }
    }
    // Figure out how to convert back to object type...
}

答案 1 :(得分:2)

这是一个老问题,但答案对我不起作用。

我必须将我的swift对象更改为NSObject以使其工作,并且还具有动态属性。

在我的情况下,我使用pod Marshal反序列化数据。

 class MyClass: NSObject, Unmarshaling
  {
       // @objc dynamic make property available for NSObject
       @objc dynamic var myProperty: String?

       required init(object: MarshaledObject) throws {
          super.init()

          initUsingReflection(object: object)
        }

        func initUsingReflection(object: MarshaledObject) {
          let mirror = Mirror(reflecting: self)

          // we go through children
          for child in mirror.children {
            guard let key = child.label else {
              continue
            }

            // This line is here to get the value from json, in my case I already know the type I needed
            let myValue: String = try! object.value(for: key)

            // The trick is here, setValue only exist in NSObject and not in swift object.
            self.setValue(myValue, forKey: key)
          }
       }
  }