2022年6月15日 星期三

Swift Decodable 找不到key時,使用預設值

使用JSONDecoder時,如果找不到Key值,錯誤如下

▿ DecodingError
  ▿ keyNotFound : 2 elements
    - .0 : CodingKeys(stringValue: "b", intValue: nil)
    ▿ .1 : Context
      - codingPath : 0 elements
      - debugDescription : "No value associated with key CodingKeys(stringValue: \"b\", intValue: nil) (\"b\")."
      - underlyingError : nil

其實只要利用KeyedDecodingContainer的decode(type:forKey)就可以解決這問題

protocol Init {
    init()
}

extension KeyedDecodingContainer {
    func decode<T: Codable & Init>(_ type: T.Type,
                forKey key: Key) throws -> T {
        try decodeIfPresent(type, forKey: key) ?? .init()
    }
}

之後只要將Codable後面,加上Init這個protocal就可以了

enum B: Int, Codable {
    case one = 1
    case two = 2
}

extension B: Init {     init() {         self = .one     } }