Skip to content

Instantly share code, notes, and snippets.

@i0sa
Last active June 15, 2020 10:20
Show Gist options
  • Save i0sa/b8ff55e881b3e764ebdcedeec476bc26 to your computer and use it in GitHub Desktop.
Save i0sa/b8ff55e881b3e764ebdcedeec476bc26 to your computer and use it in GitHub Desktop.
Codable+IntString.swift
struct MyStruct: Codable {
let price: Int?
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let intPrice = try? container.decode(Int?.self, forKey: .price){
self.price = intPrice
} else if let stringPrice = try? container.decode(String.self, forKey: .price){
self.price = Int(stringPrice) ?? nil
} else {
self.price = nil;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment