If a function can return a value itself then why need to call non escaping closure to return value? Consider following example
func add(a: Int, b: Int, completion: (Int) -> ()) {
let addition = a + b
completion(addition)
}
For example, a
and b
parameters must be a positive numbers by some reason. There are 3 way to workaroud this case:
1) You can add this check in a function that calls add
. If you do so you will repeat this code any time before add
calling. It's a bad idea because of code duplication; 2) You can add this check in the add
method and return an error to a closure. In any closure you have to handle this error even if you don't want to execute any code at this case. So it's not a good idea too; 3) You can add this check in the add
method and return a boolean value showing a correctness of parameters. If parameters is correct you calculate a result and call the closure like in this code:
func add(a: Int, b: Int, completion: (Int) -> ()) -> Bool {
guard a > 0, b > 0 else {
return false
}
let addition = a + b
completion(addition)
return true
}
if !add(a: someA, b: someB, completion: {sum in print(sum)}) {
print("Wrong numbers!")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With