class Person:NSObject{
var name:String
var age:Int
init(dic:[String:AnyObject]) {
name = (dic["name"] as? String) ?? ""
age = (dic["age"] as? Int) ?? 0
}
}
let dic:[String:AnyObject] = ["name":"yijiang" as AnyObject,"age123":19 as AnyObject]
let p = Person(dic: dic)
p.name //"yijiang"
p.age //0
二贝奇、利用KVC字典轉(zhuǎn)模型:
class Student:NSObject{
var name:String = ""
var age:Int = 0
//KVC:使用KVC之前虹菲,必須保證自身初始化完畢,self調(diào)用父類的init
//在KVC之前掉瞳,必須保證當(dāng)前對(duì)象里面所有的“非可選”屬性有值
init(dic:[String:AnyObject]) {
super.init()
setValuesForKeys(dic)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
print(value,key)
}
}
let dic1:[String:AnyObject] = ["name":"yijiang" as AnyObject,"age1":18 as AnyObject]
let s = Student(dic: dic1)
s.age //0
s.name //yijiang