在OC中用慣了JSONModel,養成了一個習慣:所有的字段都用string接。
無疑,在OC 中,繼承自JSONModel的模型裡的屬性都定義成string會避免一些空值時的報錯,以及一些不是每次都有的字段鎖造成的報錯。
然而就是這個習慣,在swift3.0中坑了我一天!因為swift轉模型時必須對應字段類型,而且在網上搜的一些代碼、例子也都沒說到這個點子上。默默的找啊找,找啊找;總算頓悟了��O(∩_∩)O哈哈~
下邊就上代碼吧,提醒下自己提醒下那些像我一樣踩到這個坑裡的朋友,但願能提供些幫助吧。
import UIKit
class ShopModel: NSObject {
/*
大體的網絡資料的格式
"resturantList":
[
{
"id": ,
"companyId": ,
"restaurantName": "AlfredShanghai",
"type": ,
"description": "eee44",
"email": "[email protected]",
"address1": "88882331",
"address2": "8888233",
"distance": ,
"avgPrice": ,
"channel": "披薩/報攤",
"telNo": "888888",
"country": "Singapore",
"state": "",
"city": "Singapore",
"postalCode": "8888",
"website": "",
"logoUrl": "http://139.224.17.126/upload/img/logo/ea79c1b9-eaac-4349-b938-5d65410f79f9.png",
"favoriteCount": ,
"weekStartDay": ,
"weekEndDay": ,
"openTime": "09:00",
"closeTime": "24:00",
"isOrder": ,
"isDelivery": ,
"isPayment": ,
"logoWidth": ,
"logoHeight": ,
"score": ,
"lon": "122.20863",
"lat": "32.00022"
},
*/
var id : Int =
var companyId : Int =
var restaurantName : String = ""
var type : Int =
var isOrder : Int =
var score : Int =
var channel : String = ""
var logoUrl : String = ""
var address1 : String = ""
var address2 : String = ""
var telNo : String = ""
var lon : String = ""
var lat : String = ""
class func dicToModel(list:[[String : Any]]) -> [ShopModel] {
var models = [ShopModel]()
for dict in list {
models.append(ShopModel(dict: dict))
}
return models
}
override init() {
}
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
super.setValue(value, forKey: key)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}