The closure in Swift, the block in Objective-c, is actually a thing
Declaration of 1.Closure variables
(1) Closure is an anonymous function, we can define a closure variable, and the type of the closure variable is the "function type" we described above.
Defining a closure variable is actually a variable that defines a particular function type, in the following way.
Because the closure variable does not have an initial value assigned to it, we declare it as a variable of an optional type. When in use, use! Force to open.
var
myCloure0:((Int, Int) -> Int)?
(2) We also use another common way of declaring closure variables. That is, using the keyword Typealias to define a specific function type,
We can take this type to declare a closure variable, as shown below
//定义闭包类型 (就是一个函数类型)
typealias MyClosureType = (Int, Int) -> Int
var
myCloure:MyClosureType?
2. Assigning values to closure variables
Assigning a value to a closure variable is actually a variable that assigns a function body to a function type, and the definition of the function is not very different.
But the function body that assigns a value to a closure variable contains a list of parameters, and the argument list and the real function body are separated by the keyword in.
The closure optional variable is called in the same way as the normal function, the only difference is that the function needs to be opened to be used. The assignment and invocation are as follows.
int int int inch return NUM1 + num2; } Myclosure! (ten)
Swift Closure (closure)