目標(biāo): 像使用字典一樣方便快捷的使用Decodable,如
init(from decoder: Decoder) throws {
let dc = try decoder.container(keyedBy: OrderCodingKey.self)
msg = try c[.msg, String.self]()
code = try c[.code](Int.self)
bankNum = dc[.bankNum, String.self] ?? ""
id = dc[.id](Int.self) ?? 0
}
遇到的問題
在使用Decodable的時候如果后臺返回的字段名稱以及類型跟我們定義struct的一樣時,那我們此時的心情是愉快的。
但是,通常這種情況很少見,更多的是需要我們自己實現(xiàn)CodingKey協(xié)議和init(from decoder: Decoder) throws方法。
例如有下面一個struct:
struct Student {
let name: String
let sex: Sex
let age: Int
let scores: Double?//此字段可能不存在,并且后臺返回的是字符串類型
let friends: Int
let books: [String] //此字段可能不存在
let pic: URL?
let area: String? //此字段可能不存在
let height: Float//此字段可能不存在,并且后臺返回的是字符串類型
let weight: Float? //后臺返回的是字符串類型
}
enum Sex: String {
case man, woman
}
extension Sex: Decodable {
enum CodingKeys: String, CodingKey {
case f, m
}
}
我們需要使用一下CodingKey
enum CodingKeys: String, CodingKey {
case name
case sex = "gender"
case age
case scores = "t_scores"
case friends = "friendsCount"
case books
case pic = "icon"
case area
case height = "t_height"
case weight = "t_weight"
}
我們通常的寫法如下:
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
name = try c.decode(String.self, forKey: .name)
sex = try c.decode(Sex.self, forKey: .sex)
age = try c.decode(Int.self, forKey: .age)
if let s = try c.decodeIfPresent(String.self, forKey: .scores) {
scores = Double(s)
} else {
scores = 0
}
friends = try c.decode(Int.self, forKey: .friends)
books = try c.decodeIfPresent([String].self, forKey: .books) ?? []
pic = try c.decode(URL.self, forKey: .pic)
area = try c.decodeIfPresent(String.self, forKey: .area)
if let h = try c.decodeIfPresent(String.self, forKey: .height) {
height = Float(h) ?? 100
} else {
height = 100
}
weight = try c.decodeIfPresent(Float.self, forKey: .weight)
}
通過以上``` init(from decoder: Decoder) throws````我們可以把具體情況大致分為4種:
1:如果某個字段后臺一定返回,并且其返回類型也跟我們需要的類型一致
這個時候是最方便快捷的,代碼量最少,如name/age字段
name = try c.decode(String.self, forKey: .name)
age = try c.decode(Int.self, forKey: .age)
2:如果某個字段后臺一定返回,但是返回類型跟我們需要的類型不一致
這個時候我們就要做一些轉(zhuǎn)化了,如weight字段
let w = try c.decode(String.self, forKey: .weight)
weight = Float(w)
這里我們就看到代碼量增加了,因為需要把后臺返回的字段轉(zhuǎn)換成需要的字段,常見的是String字段轉(zhuǎn)化為Int/Double/Float/URL.....
3:如果某個字段后臺不一定返回,但是返回類型跟我們需要的類型一致
代碼量稍微增加了一些,如books字段
books = try c.decodeIfPresent([String].self, forKey: .books) ?? []
4:如果某個字段后臺不一定返回,但是返回類型跟我們需要的類型也不一致
代碼量稍微增加了一些,如scores/height字段
if let s = try c.decodeIfPresent(String.self, forKey: .scores) {
scores = Double(s)
} else {
scores = 0
}
if let h = try c.decodeIfPresent(String.self, forKey: .height) {
height = Float(h) ?? 100
} else {
height = 100
}
可以看到這個時候代碼量大大的增加了
過程:這時想要實現(xiàn)目標(biāo),就要自定義下標(biāo)subscript
這時要針對上面的4種情況來分別實現(xiàn)對應(yīng)subscript
1:字段一定存在,并且類型也一致
public subscript<T>(key: KeyedDecodingContainer<K>.Key, sourceType: T.Type) -> () throws -> T where T: Decodable {
return { try self.decode(sourceType, forKey: key) }
}
為了拋出錯誤,自定義subscript也要拋出錯誤,方便debug。注意在使用subscript的時候是不允許throws,這里我們借助返回() throws -> T 來拋出這個錯誤
使用方法:
name = try c.decode(String.self, forKey: .name)
name = try c[.name, String.self]()
2:字段不一定存在,但是類型一致
public subscript<T>(key: KeyedDecodingContainer<K>.Key, sourceType: T.Type) -> T? where T: Decodable {
guard let value = try? self.decodeIfPresent(sourceType, forKey: key) else {
return nil
}
return value
}
這里去掉了拋出錯誤,直接返回可選值
使用方法:
area = try c.decodeIfPresent(String.self, forKey: .area)
area = try c[.area, String.self]
3:字段一定存在,但是類型不一致
這里常見的就是無論什么類型,后臺都返回給我們字符串,比如Int,Double,Float,Bool,Int8,Int16,UInt8等等,為了通用,我們需要定義一個協(xié)議
public protocol ConvertFromString {
init?(s: String)
}
然后把需要轉(zhuǎn)化的類型遵守ConvertFromString協(xié)議即可,比如:
extension Double: ConvertFromString {
public init?(s: String) {
guard let d = Double(s) else {
return nil
}
self = d
}
}
extension Bool: ConvertFromString {
public init?(s: String) {
switch s {
case "0", "false", "False", "FALSE":
self = false
case "1", "true", "True", "TRUE":
self = true
default:
return nil
}
}
}
這里為了保持和系統(tǒng)方法的一致,我們可以把一定存在的字段拋出的錯誤繼續(xù)拋出,這里同樣需要throws
public subscript<T>(key: KeyedDecodingContainer<K>.Key) -> (T.Type) throws -> T where T: Decodable & ConvertFromString {
func covertValueFromString(_ str: String, to targetType: T.Type) throws -> T {
if let v = targetType.init(s: str) {
return v
}
throw ConvertFromStringError.default
}
return { targetType in
let value = try self.decode(String.self, forKey: key)
return try covertValueFromString(value, to: targetType)
}
}
ConvertFromStringError是一個自定義的錯誤類型
public struct ConvertFromStringError: Error, CustomStringConvertible, CustomDebugStringConvertible {
public static var `default` = ConvertFromStringError()
public var description: String {
return "can not covert value from String"
}
public var debugDescription: String {
return "can not covert value from String"
}
}
使用方法:
let w = try c.decode(String.self, forKey: .weight)
weight = Float(w)
weight = try c[.weight](Float.self)
4:字段不一定存在,類型也不一致
public subscript<T>(key: KeyedDecodingContainer<K>.Key) -> (T.Type) -> T? where T: Decodable & ConvertFromString {
return { targetType in
guard let value = try? self.decodeIfPresent(String.self, forKey: key) else {
return nil
}
guard let v = value else { return nil }
return targetType.init(s: v)
}
}
使用方法:
if let s = try c.decodeIfPresent(String.self, forKey: .scores) {
scores = Double(s)
} else {
scores = 0
}
scores = c[.scores](Double.self)