Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save erikbasargin/c7b449247eb04908c137a2a81dddd3da to your computer and use it in GitHub Desktop.

Select an option

Save erikbasargin/c7b449247eb04908c137a2a81dddd3da to your computer and use it in GitHub Desktop.
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