Skip to content

Instantly share code, notes, and snippets.

@magnuskahr
Last active May 28, 2019 12:29
Show Gist options
  • Save magnuskahr/49503e627d70c59253a3c570d4786ff9 to your computer and use it in GitHub Desktop.
Save magnuskahr/49503e627d70c59253a3c570d4786ff9 to your computer and use it in GitHub Desktop.
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