- 首先定義基類繼承NSObject和實(shí)現(xiàn)HandyJSON協(xié)議 并實(shí)現(xiàn)HandyJSON要求的init方法
class ZBaseModel: NSObject, HandyJSON {
required override init() {
}
}
- 定義協(xié)議類型 并實(shí)現(xiàn)
protocol ZAutoParse {
}
extension ZAutoParse where Self: ZBaseModel {
///自動(dòng)解析成對(duì)象
static func object(from obj: Any?) -> Self {
if obj == nil {
return Self()
}
let dic = obj as? [String: Any]
return deserialize(from: dic) ?? Self()
}
///自動(dòng)解析成對(duì)象數(shù)組
static func list(from obj: Any?) -> [Self] {
if obj == nil {
return [Self]()
}
let dic = obj as? [Any]
return [Self].deserialize(from: dic)?.compactMap{$0} ?? [Self]()
}
}
- 讓ZBaseModel 遵守ZAutoParse協(xié)議即可
class ZBaseModel: NSObject, HandyJSON, ZAutoParse {
.......
}
- 實(shí)例
let aaa = ZBannerModel.list(from: response["banner_list"]
直接用自定義的子類調(diào)用相應(yīng)的轉(zhuǎn)模型或者轉(zhuǎn)模型數(shù)組方法即可。省去每次的綴余代碼。