swift - Swift function with both completion handler and return
问题描述
How do I make so that a Swift function returns a value and has a completion handler at the same time? The idea is that the function first returns a provisional result, and then the final result. Something like:
func method(completion: (Int) -> ()) {
return 2
... some processing ...
completion(3)
}
let a:Int = method(completion: { (new) -> Void in
a = new
})
解决方案
You got it upside down. You have to use the completion handler for the intermediate results and the return for the final result. Once you call the return, the control comes out of the function.
func method(completion: (Int) -> ()) -> Int {
completion(1)
//
//
completion(2)
//
//
return 3
}
And handle the result like this.
let a: Int = method(completion: { (new) -> Void in
print(new)
})
print(a)
OR
Have two completion handlers instead.
func foo(provisionalCompletion: (Int) -> (), finalCompletion: (Int) -> ()) {
provisionalCompletion(someValue)
//
//
provisionalCompletion(someValue)
//
//
finalCompletion(finalValue)
}
You can invoke it and handle the intermediate results and final results like this.
foo(completion: { (provisionalValue) in
// Handle provisional value
}) { (finalValue) in
// Handle final value
}
The second approach is more flexible, but also confusing sometimes. You have to be careful to call the final completion only when you have reached the final result. Or you could add a return after every final. But then again you have to make sure your final result is reached.
推荐阅读
- java - xpath.evaluate 可以从节点(列表)获取输入吗?
- php - Laravel 外部类文件
- ios - iOS Swift 如何同步图表绘制线条、渐变和圆形动画?
- haskell - 如何处理一元返回值`m (Maybe Foo)`?
- ios - 如何从 ViewControllers 传递数据并将它们显示到 tableviewCell 中?
- url - 单击链接不起作用,但在浏览器中复制粘贴链接有效
- php - 无缓冲查询错误 - 如何在本地主机上获取它们
- r - 如何使用其他人的条件语句在数据框中添加具有相似名称的新变量?
- excel - 硬编码范围有效,但使用命名范围失败 - Excel VBA
- javascript - 有没有办法改进此代码以避免大型数组超时?