Last active
May 28, 2019 12:29
-
-
Save magnuskahr/49503e627d70c59253a3c570d4786ff9 to your computer and use it in GitHub Desktop.
Decode arrays where items can fail: https://magnuskahr.dk/2019/05/28/decode-array-where-items-can-fail.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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