Skip to content

Instantly share code, notes, and snippets.

@tsarikovskiy
Created January 8, 2020 15:35
Show Gist options
  • Select an option

  • Save tsarikovskiy/297d710aa64e1cd82a8b9714b6e2dc3a to your computer and use it in GitHub Desktop.

Select an option

Save tsarikovskiy/297d710aa64e1cd82a8b9714b6e2dc3a to your computer and use it in GitHub Desktop.
protocol DefaultDecodable: Decodable {
associatedtype FallbackType: Decodable
static var fallback: FallbackType { get }
}
extension KeyedDecodingContainerProtocol {
func decodeValue<T: DefaultDecodable>(_ type: T.Type, forKey key: Self.Key) throws -> T {
return try decodeIfPresent(type, forKey: key) ?? T.fallback as! T
}
}
extension String: DefaultDecodable {
static var fallback: String {
""
}
}
extension Int: DefaultDecodable {
static var fallback: Int {
0
}
}
extension Bool: DefaultDecodable {
static var fallback: Bool {
false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment