Skip to content

Instantly share code, notes, and snippets.

@olivaresf
Last active January 8, 2016 03:03
Show Gist options
  • Save olivaresf/8d34efeb3bc2e6d6278c to your computer and use it in GitHub Desktop.
Save olivaresf/8d34efeb3bc2e6d6278c to your computer and use it in GitHub Desktop.
An easy way to fix your two-closure Swift indentation
// A beautiful two-closure method.
signInUser("fer", pass: "quetzalmx") { User in
// Success
print(User)
}.onFailure { error in
// Failure
print(error)
}
// Calls a function that returns an object which can optionally fail.
func signInUser(username: String, pass: String, successBlock: User -> ()) -> QuetzalRequest {
let request = // Create your Alamofire.Request
return QuetzalRequest(withRequest: request) { response, data in
// Do something with 100% valid data and response.
// If anything happens just throw.
guard let validUser = transform(data) else {
throw MyTransformError
}
successBlock(validUser)
}
}
// Our wrapper object.
// It's basically a wrapper that holds general logic for all our calls:
// check valid httpResponse and check valid data
// if neither is good, call your error closure.
class QuetzalRequest {
let request: Alamofire.Request
private var errorClosure: NSError -> () = { error in }
init(withRequest request: Alamofire.Request, onSuccess: (response: NSHTTPURLResponse, data: NSData) throws -> ())
{
self.request = request
self.request.validate().responseData { response in
if let error = response.result.error {
self.errorClosure(error)
}
guard let receivedResponse = response.response else {
self.errorClosure(MyCustomResponseError)
}
guard let receivedData = response.data else {
self.errorClosure(MyCustomNoDataError)
}
do {
try onSuccess()
} catch let error as NSError {
self.errorClosure(error)
}
}
func onFailure(errorClosure: (NSError -> ())) {
self.errorClosure = errorClosure
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment