Closures are functional self-contained modules that can be passed and used in code. Closures in Swift are similar to those in the blocks in C and Objective-c and Lambdas in other programming languages.
There are three main types of closures:
1. A global function is a closed packet that has a name but does not capture any value
2. A nested function is a closure that has a name and can capture the values in its enclosing function domain
3. A closure expression is a non-named closure that is written with lightweight syntax that captures variables or constant values in its context
Swift's closure expressions have a concise style and encourage the implementation of syntax optimizations in common scenarios, mainly optimized as follows:
* Use context to infer parameters and return value types
* Single-expression (single-expression) closure can omit the return keyword
* Parameter name Shorthand
* Trailing closure Syntax (closing 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 expressions:
1 var nums = [1,9,2,8]2in//in Parameter and split line for return value and closure body 3return num1 > num24})5 println (nums)//[9, 8, 2, 1]
Simplifying closure function Expressions: (Syntax optimization)
1 var nums = [1,9,2,8]2in//in Parameter and split line for return value and closure body 3 return num1 > num24 }) 5 println (nums)//[9, 8, 2, 1]
Again Jane:
1 var nums = [1,9,2,8]2 sort (&nums,{$0 > $1})//$ Arepresents the first parameter, $3 for the second parameter println (nums)//[9, 8, 2, 1]
Again Jane:
1 var nums = [1,9,2,8]2 sort (&nums,>)// the implementation of the greater than sign (>) defined by the type directly in the array of Swift, Func > (Lhs:int, Rhs:int), Bool3 println (nums)/ /[9, 8, 2, 1]
Trailing closure syntax (end closure)
When a closure expression is passed as the last argument to a function, we can use the trailing closure to enhance readability, and the above example can be written as follows:
1var nums = [1,9,2,8]2 //this notation3Sort (&nums) {num1,num2-Boolinch //in parameter and split line of return value and closure body4 returnNUM1 >num25 }6 //this notation7Sort (&nums) {8 return$0> $19 }Ten //However, if you are using a declared function, you can only use this OneSort (&nums,>) Aprintln (Nums)//[9, 8, 2, 1]
For example, the filtering of arrays can be easily written like this:
1 var nums = [1 , 9 , 2 , 8 2 var test = nums.filter {num-, Bool Span style= "color: #0000ff;" >in 3 return num%3 = = 0 // filters out numbers that cannot be divisible by 3 4 5 println (test) // [9]
1 var test = Nums.filter {2 return $0%30// filter out the number of 3} that cannot be divisible by 3
Swift Closed-Packet expression