- 字典转模型(初始化时传入字典)
- 字典转模型(利用KVC转化)
一、 普通的字典转模型:
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字典转模型:
class Student:NSObject{
var name:String = ""
var age:Int = 0
//KVC:使用KVC之前,必须保证自身初始化完毕,self调用父类的init
//在KVC之前,必须保证当前对象里面所有的“非可选”属性有值
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