Created
October 21, 2020 21:46
-
-
Save erikbasargin/c7b449247eb04908c137a2a81dddd3da to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T { | |
| let topLevel: Any | |
| do { | |
| topLevel = try JSONSerialization.jsonObject(with: data) | |
| } catch { | |
| throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error)) | |
| } | |
| let decoder = __JSONDecoder(referencing: topLevel, options: self.options) | |
| guard let value = try decoder.unbox(topLevel, as: type) else { | |
| throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value.")) | |
| } | |
| return value | |
| } | |
| // MARK: - Concrete Value Representations | |
| private extension __JSONDecoder { | |
| ... | |
| func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? { | |
| return try unbox_(value, as: type) as? T | |
| } | |
| func unbox_(_ value: Any, as type: Decodable.Type) throws -> Any? { | |
| ... { | |
| return try type.init(from: self) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment