目标: 像使用字典一样方便快捷的使用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的一样时,那我们此时的心情是愉快的。
但是,通常这种情况很少见,更多的是需要我们自己实现CodingKey
协议和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:如果某个字段后台一定返回,但是返回类型跟我们需要的类型不一致
这个时候我们就要做一些转化了,如weight字段
let w = try c.decode(String.self, forKey: .weight)
weight = Float(w)
这里我们就看到代码量增加了,因为需要把后台返回的字段转换成需要的字段,常见的是String字段转化为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
}
可以看到这个时候代码量大大的增加了
过程:这时想要实现目标,就要自定义下标subscript
这时要针对上面的4种情况来分别实现对应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等等,为了通用,我们需要定义一个协议
public protocol ConvertFromString {
init?(s: String)
}
然后把需要转化的类型遵守ConvertFromString协议即可,比如:
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
}
}
}
这里为了保持和系统方法的一致,我们可以把一定存在的字段抛出的错误继续抛出,这里同样需要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)