使用方法eg:
struct Model {
let app: String
let quota: Double
let rate: String
let time: String
let id: Int
let icon: URL?
let url: URL? // 这个字段可能为空
}
extension Model: Codable {
enum ModelCodingKey: String, CodingKey {
case app = "name"
case quota = "amount"
case rate = "interest"
case time = "term"
case id
case icon = "logoUrl"
case url = "linkeUrl"
}
}
let c = try decoder.container(keyedBy: ModelCodingKey.self)
1: 解放decode(type, forKey: key)
app = try c[.app, String.self]()
2: 解放 decodeIfPresent----第三个参数是设置默认值的
url = c[.url, URL.self, nil]
3: 方便快捷的把后台String类型转化为Int/Double/Float/URL......(如果想使用默认值可以使用??)
icon = c[.icon, URL.self] // 因为某些带中文的url无法解析,so。。。。。
id = c[.id, Int.self] ?? 0
quota = c[.quota, Double.self] ?? 0