Last active
September 14, 2019 11:07
-
-
Save r-plus/0d243272ac2247305551100c129da344 to your computer and use it in GitHub Desktop.
method for don't throw Swift.Error and keep default value if key is not present in json.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension KeyedDecodingContainerProtocol { | |
func decode<T: Decodable>(into: inout T, forKey key: Self.Key) { | |
guard let tmp = try? self.decode(T.self, forKey: key) else { return } | |
into = tmp | |
} | |
} | |
class A: Decodable { | |
var hoge = "1" | |
enum CodingKeys: CodingKey { | |
case hoge | |
} | |
required init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
container.decode(into: &hoge, forKey: .hoge) | |
} | |
} | |
let str = "{}" | |
let data = str.data(using: .utf8)! | |
let d = JSONDecoder() | |
let a2 = try! d.decode(A.self, from: data) | |
print(a2.hoge) // 1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment