為Decodable添加subscript擴展

目標(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)

博客地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 參考文章《JNA:JAVA調(diào)用DLL 超詳細(xì)代碼實戰(zhàn)》和《JNAExamples》實現(xiàn)了java和c實現(xiàn)的dll相...
    oracle3閱讀 604評論 0 0
  • 今天是星期日,我對孩子說,你己經(jīng)四年級了,我再不能總這樣陪你寫作業(yè),我也上班,我也很忙。我相信你可以自已獨...
    松鼠家閱讀 231評論 0 0
  • 什么叫戰(zhàn)略?克勞塞維茨,在他的不朽名著《戰(zhàn)爭論》中,這樣定義戰(zhàn)略:戰(zhàn)略是為了達到戰(zhàn)爭目的而對戰(zhàn)斗的運用。因此,戰(zhàn)略...
    我是曾小清閱讀 220評論 0 0
  • 姓名:張漢超 公司:東莞耀升機電有限公司 組別:4月25-27日六項精進245期學(xué)員 【日精進打卡第136天】 【...
    張漢超閱讀 191評論 0 0

友情鏈接更多精彩內(nèi)容