首页 > 解决方案 > 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
})

标签: swift

解决方案


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.


推荐阅读