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

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

在与后台通过 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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容