Created
June 15, 2022 10:29
-
-
Save yycking/0a01521c7cde48c11f711b3fd93950f6 to your computer and use it in GitHub Desktop.
Codable + default value
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
protocol Init { | |
init() | |
} | |
extension KeyedDecodingContainer { | |
func decode<T: Codable & Init>(_ type: T.Type, | |
forKey key: Key) throws -> T { | |
try decodeIfPresent(type, forKey: key) ?? .init() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
test code
`enum B: Int, Codable {
case one = 1
case two = 2
}
extension B: Init {
init() {
self = .one
}
}
struct A: Decodable {
let b: B
}
let data = try JSONSerialization.data(withJSONObject: [:])
let a = try JSONDecoder().decode(A.self, from: data)
`