Skip to content

Instantly share code, notes, and snippets.

@crayment
Created April 23, 2016 23:00
Show Gist options
  • Save crayment/29b12180840a4846a59ea530e319c23c to your computer and use it in GitHub Desktop.
Save crayment/29b12180840a4846a59ea530e319c23c to your computer and use it in GitHub Desktop.
struct MasterResponse<T: JSONDecodable> {
let object: T?
let error: [String: JSON]?
}
extension MasterResponse: JSONDecodable {
init(json: JSON) throws {
guard case let .Dictionary(jsonDictionary) = json else {
let error = JSON.Error.ValueNotConvertible(value: json, to: MasterResponse.self)
throw error
}
let error: [String: JSON]? = {
guard let errorDictionary = jsonDictionary["error"], case let .Dictionary(error) = errorDictionary else { return nil }
return error
}()
let object: T? = {
guard let objectDictionary = jsonDictionary["object"], let object = try? T(json: objectDictionary) else { return nil }
return object
}()
guard object != nil || error != nil else { // Enforce having either an object or an error
let error = JSON.Error.ValueNotConvertible(value: json, to: MasterResponse.self)
throw error
}
self.object = object
self.error = error
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment