Skip to content

Instantly share code, notes, and snippets.

View randomguy0815's full-sized avatar

Alexander Anderl randomguy0815

View GitHub Profile
struct EnumModelRawValue: Decodable {
   
enum Keys: CodingKey {
case status
}
   
enum Status: String {
case enabled
case disabled
   
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Keys.self)
   
self.status = try? Container.decodeIfPresent(Status.self, forKey: .status) ?? .disabled
}
{
"status": "new"
}
struct EnumModelIfPresent: Decodable {
   
enum Keys: CodingKey {
case status
}
   
enum Status: String, Decodable {
case enabled
case disabled
}
Decoding method Value Null Attribute Missing Null element Invalid element
synthesized [Int] property
decode([Int], ...)
decode([Int]?, ...)
synthesized [Int]? property
decodeIfPresent([Int], ...)
decode([Int?]?, ...)
decodeArrayOmitingInvalidObjects([Int], ...)
struct DummyDecodable: Decodable {}
extension KeyedDecodingContainer {
   
func decodeArrayOmitingInvalidObjects<T: Decodable>(forKey key: KeyedDecodingContainer.Key) -> [T] {
   
guard var nestedUnkeyedContainer = try? self.nestedUnkeyedContainer(forKey: key) else {
return []
}
var result = [T]()
{
"array": [
1,
"2",
3
]
}
{
"array": [
1,
null,
3
]
}
{
"array": [
1,
2,
3
]
}