Created
April 23, 2016 23:00
-
-
Save crayment/29b12180840a4846a59ea530e319c23c 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
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