Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment