Swift 对象初始化中通过反射访问属性

作者: 公爵海恩庭斯 | 来源:发表于2016-01-08 18:07 被阅读249次

    以这样的方式构造对象其实并不推荐。

    在与后台通过 Json 通信时,我们通常需要用到大量的数据结构类,并书写大量的代码逻辑,负责将 Json 对象转化为对应的数据结构对象。这些繁琐的代码逻辑浪费了我们太多时间。我们可以通过反射访问实例属性的方法,来简化我们的开发,节约时间:

    class MyObject: NSObject {
        var name: String?
        var type: String?
        var anyOther: String?
        // ...
        
        init(dict: Dictionary<String, AnyObject>) {
            super.init()
            
            let children = Mirror(reflecting: self).children.filter { $0.label != nil }
            for child in children {
                self.setValue(dict[(child.label ?? "")], forKey: child.label!)
            }
        }
    }
    
    var properties = [String: AnyObject]()
    properties["name"] = "Heistings"
    properties["type"] = "Human"
    properties["someOtherKey"] = "someOtherValue"
        
    let a = MyObject(dict: properties)
        
    print(a.name ?? "Not initalized") // John
    print(a.type ?? "Not initalized") // Human
    print(a.anyOther ?? "Not initalized") // Not initalized
    

    相关文章

      网友评论

        本文标题:Swift 对象初始化中通过反射访问属性

        本文链接:https://www.haomeiwen.com/subject/bpafkttx.html