Last active
January 8, 2016 03:03
-
-
Save olivaresf/8d34efeb3bc2e6d6278c to your computer and use it in GitHub Desktop.
An easy way to fix your two-closure Swift indentation
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
// 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