Skip to content

Instantly share code, notes, and snippets.

@yycking
Created June 15, 2022 10:29
Show Gist options
  • Save yycking/0a01521c7cde48c11f711b3fd93950f6 to your computer and use it in GitHub Desktop.
Save yycking/0a01521c7cde48c11f711b3fd93950f6 to your computer and use it in GitHub Desktop.
Codable + default value
protocol Init {
init()
}
extension KeyedDecodingContainer {
func decode<T: Codable & Init>(_ type: T.Type,
forKey key: Key) throws -> T {
try decodeIfPresent(type, forKey: key) ?? .init()
}
}
@yycking
Copy link
Author

yycking commented Jun 15, 2022

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)
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment