[英]Swift: Call closure complete method in a different function
I'd like to use a method that return a result asynchronously using the delegate pattern within a closure. 我想使用在闭包内使用委托模式异步返回结果的方法。
Is it possible to reference the complete block within another function within the same class? 是否可以在同一类的另一个函数中引用完整块?
class A {
func performASyncTask(input:String, complete:(result:String) -> Void) {
let obj = Loader()
obj.delegate = self
obj.start()
// Loader() returns loaderCompleteWithResult(result:String) when completed
}
func loaderCompleteWithResult(result:String){
// Call complete function in performASyncTask .e.g
complete(result); // Calls the complete function in performASyncTask
}
}
I don't really understand what do you want to achieve. 我不太了解您要实现什么目标。 But you can declare function property and use it later:
但是您可以声明函数属性并在以后使用:
class A {
var closureSaver: ((result:String) -> Void)?
func performASyncTask(input:String, complete:(result:String) -> Void) {
let obj = Loader()
obj.delegate = self
obj.start()
closureSaver = complete
complete(result: "a")
}
func loaderCompleteWithResult(result:String){
closureSaver?(result:result)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.