JSONExport 转换模型时候后,需要自定义更小模型时候可用Map
//用map 函数快速 转换模型 如 大模型 -> 小模型 或 小小大
struct BigModel {
var name:String!
var age:Int!
var adress:String!
var gender:String!
}
struct SmallModel {
var name:String! = ""
var age:Int! = 0
}
let bigDatas = [BigModel(name: "逗牛", age: 10, adress: "简书3515号", gender: "男"), BigModel(name: "锅盖", age: 12, adress: "某岛369号", gender: nil)]
//简写
let smallDatas = bigDatas.map { SmallModel(name: $0.name ,age: $0.age) }
//完整写法
let smallDatas2 = bigDatas.map { (bigData) -> SmallModel in
return SmallModel(name: bigData.name, age: bigData.age)
}
print(smallDatas2)
注意:服务器返回的nil数据时候
// 有时候服务器返回的数据,有可能出现空值情况
//JSONExport秒转Model 使用时候注意nil
//下面进行简单处理
let notNormalDatas = [BigModel(name: "逗牛", age: nil, adress: "冒险岛蜗牛", gender: "男"), BigModel(name: nil, age: 12, adress: "冒险岛", gender: nil)]
let notNormalData = notNormalDatas.map { (notNormalData) -> SmallModel in
var smallM = SmallModel()
if let name = notNormalData.name {
smallM.name = name
}
if let age = notNormalData.age {
smallM.age = age
}
return smallM
}
print(notNormalData)