我可以使用镜像设置Swift对象属性的值吗?

问题描述 投票:8回答:2

现在我可以使用Mirror类型检查对象的变量。但是我可以使用镜像为变量设置值吗?或许还有另一种纯粹的Swift方式?

例如,我想从JSON创建一个对象(Swift struct)。没有子类化NSObject并使用Objective-C函数可以吗?

json swift swift2 mirror mirroring
2个回答
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...
}

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)
          }
       }
  }
© www.soinside.com 2019 - 2024. All rights reserved.