swift4中字典轉(zhuǎn)BookDataModel可以使用model.setValuesForKeys(dic),model類(lèi)如下:
class BookDataModel: NSObject {
var title:String = ""
var subtitle:String = ""
init(dic:[String:Any]) {
super.init()
self.setValuesForKeys(dic)// 字典轉(zhuǎn)BookDataModel便捷方法
}
// 字典轉(zhuǎn)BookDataModel捺信,BookDataModel中沒(méi)有的key重寫(xiě)不拋出異常
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
但是發(fā)現(xiàn)轉(zhuǎn)model不成功胸墙,百度之后發(fā)現(xiàn)需要在class BookDataModel: NSObject之前加上@objcMembers修飾寸痢,然后就可以成功了囊榜。添加之后如下:
@objcMembers
class BookDataModel: NSObject {
var title:String = ""
var subtitle:String = ""
init(dic:[String:Any]) {
super.init()
self.setValuesForKeys(dic)// 字典轉(zhuǎn)BookDataModel便捷方法
}
// 字典轉(zhuǎn)BookDataModel,BookDataModel中沒(méi)有的key重寫(xiě)不拋出異常
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
在需要的地方調(diào)用就可以了:
let model = BookDataModel(dic: book)
參考鏈接:
ios swift4之kvo的使用