ios - Swift - Method chaining -
i'd implement method chaining in swift
code, alamofire
methods. example, if have use function below
getlistforid(12).success { // success block }. failure { // failure block }
how create function getlistforid
?
to expand on great points @dasblinkenlight , @sulthan have made – here's small example of how achieve request function take success , failure closure, in convenient syntax want.
first, you'll have define new class represent 'result handler'. success
, failure
functions pass around, allowing add multiple trailing closures make completion block logic. you'll want this:
class resulthandler { typealias successclosure = requesthandler.output->void typealias failureclosure = void->void // success , failure callback arrays private var _successes = [successclosure]() private var _failures = [failureclosure]() /// invoke stored callbacks given callback result func invokecallbacks(result:requesthandler.result) { switch result { case .success(let output): _successes.foreach{$0(output)} case .failure: _failures.foreach{$0()} } } // remove callbacks – call within invokecallbacks // depending on re-usability of class func removeallcallbacks() { _successes.removeall() _failures.removeall() } /// appends new success callback result handler's successes array func success(closure:successclosure) -> self { _successes.append(closure) return self } /// appends new failure callback result handler's failures array func failure(closure:failureclosure) -> self { _failures.append(closure) return self } }
this allow define multiple success or failure closures executed on completion. if don't need capacity multiple closures, can simplify class down stripping out arrays – , keeping track of last added success , failure completion blocks instead.
now have define function generates new resulthandler
instance , given asynchronous request, invokecallbacks
method being invoked upon completion:
func dorequest(input:input) -> resulthandler { let resulthandler = resulthandler() dosomethingasynchronous(resulthandler.invokecallbacks) return resulthandler }
now can call this:
dorequest(input).success {result in print("success, with:", result) }.failure { print("fail :(") }
the thing note dosomethingasynchronous
function have dispatch completion block main thread, ensure thread safety.
full project (with added example on usage): https://github.com/originaluser2/callback-closure-chaining
Comments
Post a Comment