SafeDecoder enhance the compatibility for Decodable.
github "Beyova/SafeDecoder"
import SafeDecoder
class User: Codable {
var id: Int
}
let decoder = SafeDecoder()
let data = try JSONSerialization.data(withJSONObject: ["id": "42"], options: [])
let result = try decoder.decode(User.self, from: data)
class User: Codable {
var id: String
}
let decoder = SafeDecoder()
let data = try JSONSerialization.data(withJSONObject: ["id": 42], options: [])
let result = try decoder.decode(User.self, from: data)
enum Gender: String, Codable {
case unknown
case male
case female
}
struct User: Codable {
let gender: Gender
enum CodingKeys: String, FallbackCodingKey
case gender
func fallbackValue() -> FallbackValue {
switch self {
case .gender: return (true, Gender.unknown)
}
}
}
}
let decoder = JSONDecoder()
let data = try JSONSerialization.data(withJSONObject: [:], options: [])
let result = try decoder.decode(User.self, from: data)