Swift - 方法链接 [英] Swift - Method chaining
问题描述
我想在我的 swift
代码中实现方法链接,可能是 Alamofire
方法。例如,如果我必须使用我的函数,如下所示
I'd like to implement method chaining in my swift
code, likely to Alamofire
methods. For example, if I have to use my function like below
getListForID(12).Success {
// Success block
}. Failure {
// Failure block
}
我如何创建函数 getListForID
?
推荐答案
扩展优点@dasblinkenlight 和 @ Sulthan 已经制作了 - 这是一个小例子,说明如何使用您想要的方便语法实现请求函数以成功和失败关闭。
To expand on the great points @dasblinkenlight and @Sulthan have made – here's a small example of how you could achieve your request function to take a success and failure closure, in the convenient syntax that you want.
首先,您必须定义一个新类来表示结果处理程序。这就是你的成功
和失败
函数会传递的内容,允许你添加多个尾随闭包来弥补你的完成块逻辑。你会希望它看起来像这样:
First, you'll have to define a new class to represent the 'result handler'. This is what your success
and failure
functions will pass around, allowing you to add multiple trailing closures to make up your completion block logic. You'll want it to look something like this:
class ResultHandler {
typealias SuccessClosure = RequestHandler.Output->Void
typealias FailureClosure = Void->Void
// the success and failure callback arrays
private var _successes = [SuccessClosure]()
private var _failures = [FailureClosure]()
/// Invoke all the stored callbacks with a given callback result
func invokeCallbacks(result:RequestHandler.Result) {
switch result {
case .Success(let output): _successes.forEach{$0(output)}
case .Failure: _failures.forEach{$0()}
}
}
// remove all callbacks – could call this from within invokeCallbacks
// depending on the re-usability of the class
func removeAllCallbacks() {
_successes.removeAll()
_failures.removeAll()
}
/// appends a new success callback to the result handler's successes array
func success(closure:SuccessClosure) -> Self {
_successes.append(closure)
return self
}
/// appends a new failure callback to the result handler's failures array
func failure(closure:FailureClosure) -> Self {
_failures.append(closure)
return self
}
}
这将允许您定义在完成时执行的多个成功或失败闭包。如果你实际上并不需要多个闭包的容量,那么你可以通过剥离数组来简化类 - 而只是跟踪最后添加的成功和失败完成块。
This will allow you to define multiple success or failure closures to be executed on completion. If you don't actually need the capacity for multiple closures, then you can simplify the class down by stripping out the arrays – and just keeping track of the last added success and failure completion blocks instead.
现在你所要做的就是定义一个生成新的 ResultHandler
实例的函数,然后使用 invokeCallbacks
完成后调用的方法:
Now all you have to do is define a function that generates a new ResultHandler
instance and then does a given asynchronous request, with the invokeCallbacks
method being invoked upon completion:
func doRequest(input:Input) -> ResultHandler {
let resultHandler = ResultHandler()
doSomethingAsynchronous(resultHandler.invokeCallbacks)
return resultHandler
}
现在您可以这样调用它:
Now you can call it like this:
doRequest(input).success {result in
print("success, with:", result)
}.failure {
print("fail :(")
}
唯一需要注意的是你的 doSomethingAsynchronous
函数必须发送完成阻止回主线程,以确保线程安全。
The only thing to note is your doSomethingAsynchronous
function will have to dispatch its completion block back to the main thread, to ensure thread safety.
完整项目(添加了使用示例) : https://github.com/hamishknight/Callback-Closure-Chaining
Full project (with added example on usage): https://github.com/hamishknight/Callback-Closure-Chaining
这篇关于Swift - 方法链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!