Last active
May 3, 2023 14:14
-
-
Save cedricbahirwe/52e91f5c98fa2b80f2c37b879501604a to your computer and use it in GitHub Desktop.
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
let json = """ | |
[ | |
{ | |
"id": 1, | |
"name": "Any vs. AnyObject in Swift", | |
"type": "articles" | |
}, | |
{ | |
"id": 2, | |
"name": "New Apple silicon", | |
"type": "news" | |
}, | |
{ | |
"id": 3, | |
"name": "Passing weak self into a closure", | |
"type": "videos" | |
} | |
] | |
""".data(using: .utf8)! | |
struct ListElement: Decodable { | |
let id: Int | |
let name: String | |
let type: ElementType | |
enum ElementType: String, Decodable { | |
case articles, news | |
} | |
} | |
struct FailableDecodable<T: Decodable>: Decodable { | |
let element: T? | |
init(from decoder: Decoder) throws { | |
self.element = try? T(from: decoder) | |
} | |
} | |
struct FailableResult<T: Decodable>: Decodable { | |
let result: Result<T, Error> | |
init(from decoder: Decoder) throws { | |
result = Result(catching: { try T(from: decoder) }) | |
} | |
} | |
let elements = try JSONDecoder().decode([FailableResult<ListElement>].self, from: json).compactMap { try? $0.result.get() } | |
print(elements) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment