Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//: Playground - noun: a place where people can play
import UIKit
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
class Chainable<SuccessParams, FailureParams> {
var successClosure: ((SuccessParams) -> ())? = nil
var failureClosure: ((FailureParams) -> ())? = nil
func onSuccess(closure: (SuccessParams) -> ()) -> Chainable {
successClosure = closure
return self
}
func onFailure(closure: (FailureParams) -> ()) -> Chainable {
failureClosure = closure
return self
}
func doSuccess(params: SuccessParams) {
if let closure = successClosure {
closure(params)
}
}
func doFailure(params: FailureParams) {
if let closure = failureClosure {
closure(params)
}
}
}
class NetworkHelper {
func cacheImage(url: String) -> Chainable<String, Void> {
let chains = Chainable<String, Void>()
delay(1) {
let outcome = rand() % 2
if outcome > 0 {
print("NetworkHelper: got image")
chains.doSuccess("/dev/null")
} else {
print("NetworkHelper: a failure occured")
chains.doFailure()
}
}
return chains
}
}
let helper = NetworkHelper()
helper.cacheImage("url")
helper.cacheImage("url").onSuccess({
localURL in print("saved to local cache at \(localURL)")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.