iOS 开发技巧大全iOS开发技术分享iOS学习笔记

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

2016-01-08  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读