Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is actually use of non escaping closures?

Tags:

closures

swift

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)
 }
like image 529
Pankaj Battise Avatar asked Oct 20 '25 09:10

Pankaj Battise


1 Answers

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!")
}
like image 112
Emin A. Alekperov Avatar answered Oct 23 '25 06:10

Emin A. Alekperov