What is the difference between a swift variable and a function when using closure in a variable?

Swift closureconfuses me when used in a variable. Consider the following example.

let divide = {(val1: Int, val2: Int) -> Int in 
   return val1 / val2 
}
let result = divide(200, 20)
println(result)

Here divideis a variable, but it can take parameters. I know from another language, only a function can take parameters. So what is the difference between a variable and a function? What is the advantage when used clousurein swift variable?

+4
source share
3 answers

/ ; . , / , , , , . , / , -

, "" . , , , . , :

class MyViewController : ViewController {
  func takeAction (message:String) {
    // do some stuff, then
    doComputation { 
      self.dismissViewController()
      NSLog ("took action: \(message)")
    }
  }
}   

doComputation ; , self message .

0

Closure - ( ), viewcontroller, , - ( /, ,...),

, U ( ),

+2

, . . , , , .

psuedo:

class aaa {

  var a = 5;

  func foo (b:Int) -> Int {
     return a+b;  //a not defined in local scope, but we can still use it
  }
}

now with closing it is the same thing, but you can use local variables in the same way as using a variable defined at the class level

class bbb {

  var b = 1;
  var closure;

  func foo (c:Int) -> Int {
     var d = b+c; //d is defined locally
     closure = (val1:Int) -> Int { Int in
       return val1 + b * d; //we can use b and d here! they are captured in the block now, and will remain with the block until executed
     }
  }

  func bar () {

    b = 3;

    closure(5); //now we execute closure, now the variable d in foo() is being used but in a completely different scope, and even if we changed the value of b before running it, the value of b would be the original value captured in the closure when it was made aka 1 and not 3
  }
}

So now, if you run foo, then you can see how closures differ from functions

therefore, the real beauty lies in capturing variables locally, which will be used later, possibly in a completely different area, where, since functions can only use the parameters that you give them, and / or variables defined in the class

0
source

Source: https://habr.com/ru/post/1618367/


All Articles