Last active
September 4, 2018 16:38
-
-
Save markiv/a336cf34a5f7436b69b9ee4ce43678ae to your computer and use it in GitHub Desktop.
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 KeyedDecodingContainer { | |
func lenientDecode<T>(_ type: T.Type, forKey key: KeyedDecodingContainer.Key) throws -> T where T: Decodable & LosslessStringConvertible { | |
do { | |
return try decode(T.self, forKey: key) | |
} catch { | |
guard let stringValue = try? decode(String.self, forKey: key), let t = T(stringValue) else { throw error } | |
return t | |
} | |
} | |
} | |
struct Stop: Codable { | |
let id: Int | |
let name: String | |
let x, y: Int? // sometimes wrongly encoded as a string "12345" | |
init(from decoder: Decoder) throws { | |
let values = try decoder.container(keyedBy: CodingKeys.self) | |
id = try values.lenientDecode(Int.self, forKey: .id) | |
name = try values.decode(String.self, forKey: .name) | |
x = try values.lenientDecode(Int.self, forKey: .x) | |
y = try values.lenientDecode(Int.self, forKey: .y) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For those times when an API throws randomly quoted numbers at you.