Decode arrays where items can fail: https://magnuskahr.dk/2019/05/28/decode-array-where-items-can-fail.html
import Foundation | |
// We provide some json and transform it to Data-type | |
let json = """ | |
[{ | |
"name": "John", | |
"startingTime": 581167640.06502903 | |
}, { | |
"name": "Mark", | |
"startingTime": 582031640.06502903 | |
}, { | |
"name": "Tobias" | |
}] | |
""".data(using: .utf8)! | |
// The struct we wonna decode to, it needs to be `Codable` | |
struct Participant: Codable { | |
let name: String | |
let startingTime: Date | |
} | |
// The wrapper type | |
struct FailableDecodable<T: Decodable>: Decodable { | |
let value: T? | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
self.value = try? container.decode(T.self) | |
} | |
} | |
// Lets decode! | |
let decoder = JSONDecoder() | |
let wrapped = try! decoder.decode([FailableDecodable<Participant>].self, from: json) | |
// Using compactMap() we can filter out every `nil` values | |
let participants = wrapped.compactMap {$0.value} | |
print(participants) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment