Swift closure expression, swift closure expression
Closures are functional self-contained modules that can be passed and used in code. Closures in Swift are similar to blocks in C and Objective-C, and lambdas in other programming languages.
There are three types of closures:
1. A global function is a closure with a name but no value is captured.
2. A nested function is a closure with a name and can capture the values in the closed function domain.
3. The closure expression is a closure written in lightweight syntax that can capture variables or constant values in its context without names.
The closure expression of Swift has a concise style and encourages syntax Optimization in common scenarios. The main optimization is as follows:
* Use context inference parameters and return value types
* A single-expression closure can omit the return keyword.
* Abbreviated parameter name
* Trailing closure syntax (ending closure)
Nested functions:
1 var nums = [1,9,2,8]2 func testF(num1 : Int, num2 : Int) -> Bool{3 return num1 > num24 }5 sort(&nums, testF)6 println(nums)//[9, 8, 2, 1]
No optimized closure expression:
1 var nums = [1, 9, 2, 8] 2 sort (& nums, {(num1: Int, num2: Int) -> Bool in // in parameter and split line between return value and closure body 3 return num1> num24}) 5 println (nums) // [9, 8, 2, 1]
Simplified closure function expressions: (syntax optimization)
5 var nums = [,] 6 sort (& nums, {(num1, num2) in // in parameter and split line between return value and closure body 7 return num1> num28 }) 9 println (nums) // [9, 8, 2, 1]
Simplicity
Var nums = [,] sort (& nums, {$0> $1}) // $0 represents the first parameter, and $1 represents the second parameter println (nums) // [9, 8, 2, 1]
Simplicity
Var nums = [,] sort (& nums,>) // directly use the implementation func> (lhs: Int, rhs: Int)-> Boolprintln (nums) // [9, 8, 2, 1]
Trailing closure syntax (end closure)
When a closure expression is passed to the function as the last parameter, we can use the ending closure to enhance readability. The above example can also be written as follows:
Var nums = [,] // This sort (& nums) {num1, num2-> Bool in // in parameter and split line between return value and closure body return num1> num2} // sort (& nums) {return $0> $1} // If a declared function is used, only the sort (& nums,>) println (nums) // [9, 8, 2, 1]
For example, array filtering can be easily written as follows:
Var nums = [1, 9, 2, 8] var test = nums. filter {num-> Bool in return num % 3 = 0 // filter out numbers not divisible by 3} println (test) // [9] var test = nums. filter {return $ 0% 3 = 0 // filter out the number that cannot be divisible by 3}