Skip to content

Instantly share code, notes, and snippets.

@markiv
Last active September 4, 2018 16:38
Show Gist options
  • Save markiv/a336cf34a5f7436b69b9ee4ce43678ae to your computer and use it in GitHub Desktop.
Save markiv/a336cf34a5f7436b69b9ee4ce43678ae to your computer and use it in GitHub Desktop.
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)
}
}
@markiv
Copy link
Author

markiv commented Feb 6, 2018

For those times when an API throws randomly quoted numbers at you.

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