Swift2.0 Language course closure Swift2.0 languageClosed Package
Closures are self-contained function code blocks that can be passed and used in code. Closures in Swift are similar to those in the code blocks (blocks) in C and Objective-c, and in other programming languages. The function described in this chapter is actually a special closure. This section mainly explains the basic use of closures.
Swift2.0 Language Closure expressions
A closure expression is a way to construct an inline (inline similar to a macro definition in C language) with a concise syntax. The following code is a comparison of two strings.
- Import Foundation
- Determine the size of a two string
- Func Compare (s1:string, s2:string), Bool {
- return s1 > S2
- }
- Let str1= "Hello"
- Let str2= "Swift"
- If compare (str1, s2:str2) {
- Print ("str1 greater than str2")
- }else{
- Print ("str1 less than str2")
- }
The results of the operation are as follows:
In this code, when the function compare () is called, str1 and str2 are passed to the function in the parameter s1,s2 when it is defined, and then compared. As you can see in this code, a line of code executed in the Compare () function is judged and returned, and this function is quite verbose. At this point, you can use the closure expression to make the code better. First, look at the syntactic form of the closure expression (the closure function).
- {(parameter list), return value type in
- Statement
- }
Where parameters can be constants, variables, and input-output parameters, but there are no default values. Developers can also use variable parameters at the end of the parameter list. Tuples can also be used as parameters and return values. The keyword in means that the closure parameter and the return value type definition are complete, and the closure function body is about to begin.
1. Non-parametric form of closure expressions
The syntax of a closed-form expression with no parameters is as follows:
- {(), return value type in
- Statement
- }
It defines the following syntax form:
- Let/var Closure expression constant name/closure expression variable name/= non-parametric form of closure expression
It is called in the following syntax form:
- Closure expression constant Name/closure expression variable name ()
Example 7-27 the following will implement the output of the string "AAAA" using a closure expression. The code is as follows:
- Import Foundation
- Output string "AAAA"
- var str={() in
- Print ("AAAA")
- }
- Call form for str () //Call
The results of the operation are as follows:
2. Closed-loop expressions with parameters
There are two forms of closure expressions with parameters, one is the most commonly used one, and the other is a closure expression with multiple parameters. The following is a detailed explanation of the two types of closure expressions with parameters.
(1 ) a closure expression with one parameter
The syntactic form of a closure expression with one parameter is as follows:
- {(Parameter name: data type), return value type in
- Statement
- }
It defines the following syntax form:
- Let/var Closure expression constant name/closure expression variable name/= closure expression with one parameter
Its invocation form is as follows:
- Closure expression constant Name/closure expression variable name ()
Example 7-28 the following will use the closure expression to output the specified string. The code is as follows:
- Import Foundation
- Outputs the specified string
- var str={(str:string) in
- Print (str)
- }
- STR ("Hello")
The results of the operation are as follows:
(2 ) A closure expression with multiple parameters
The syntax of a closure expression with multiple parameters is as follows:
- {(Parameter name 1: Data type, parameter Name 2: Data type,...) , return value type in
- Statement
- }
It defines the following syntax form:
- Let/var Closure expression constant name/closure expression variable name/= closure expression with multiple parameters
Its invocation form is as follows:
- Closure expression constant Name/closure expression variable name ()
Example 7-29 uses a closure implementation to compute the sum of two arbitrary numbers, with the following code:
- Import Foundation
- The implementation of the two-digit and
- var reversed = {(S1:int, s2:int), Int in
- var sum=s1+s2
- return sum
- }
- Print (Reversed (10,20))
The results of the operation are as follows:
In fact, the closure expression is the longest used in other functions, not to use it alone.
Example 7-30 The following code implements a closure expression as part of a function to determine whether there are elements greater than 500 or 40 in the array. The code is as follows:
- Import Foundation
- Defining functions
- Func Copare (ARR:[INT],VALUE:INT,CB: (num:int,value:int)->bool)->bool{
- Iterating through an array
- For item in arr{
- Determine if the closure is true
- if (CB (Num:item,value:value)) {
- return True
- }
- }
- return False
- }
- var array = [20,80,100,50,20]
- Use closures to determine if there are more than 500 elements in the array
- var v1=copare (ARRAY,VALUE:500,CB: {(num:int,value:int)->bool in
- Return Num>value
- })
- Determine the result and output ·
- If V1==true {
- print (" there are more than one element in an array of arrays ")
- }else{
- print (" there are no more than three elements in an array of arrays ")
- }
- Use closures to determine if there are more than 40 elements in the array
- var v2=copare (ARRAY,VALUE:40,CB: {(num:int,value:int)->bool in
- Return Num>value
- })
- Judging the result and outputting
- If V2==true {
- print (" there are more than one element in an array of arrays ")
- }else{
- print (" There is no element larger than the size of the array")
- }
In this code, when the Copare () function is called, the parameter array, 40, and the closure expression are passed to the parameters of the function definition, and the closure expression is called when the element in the array is traversed in the Copare () function. The results of the operation are as follows:
- Arrays Array no more than The big element
- Arrays Array there is a ratio of The big element
Considerations for Swift2.0 language using closure expressions
There are a few things to note when using a closure expression (as illustrated in example 7-30 below):
1. Inferred type
The third parameter of the Copare () function is the closure expression, which is of type (Num:int,value:int)->bool, because Swift can infer the type of its parameter and return value, so and the parentheses around the parameter can be omitted, such as the following code:
- var v1=copare (array,value:500,cb:{(Num,value) in
- Return Num>value
- })
2. Omit return
A single-line expression closure can implicitly return the result of a single-line expression by hiding the return keyword, and you can modify the above example:
- var v1=copare (array,value:500,cb:{(Num,value) in
- Num>value
- })
3. Name of the parameter
Swift provides the parameter name abbreviation function for the inline function, and the developer can call the closure parameters in order of $, $, $. If you use a parameter name abbreviation in a closure expression, you can omit the definition of it in the closure parameter list, and the type that corresponds to the abbreviation for the parameter name is inferred from the function type. The In keyword can also be omitted, because at this point the closure expression is completely composed of the closure function body, and the above example is modified:
- var v1=copare (Array, VALUE:500,CB: {
- $ > $
- })
4. Write on a line
When the function body portion of the closure is very short, it can be written on one line, such as the following code:
- var v1=copare (ARRAY,VALUE:500,CB: {$ > $})
5. Operator functions
In Swift, the string type defines the implementation of the strings for the greater-than sign (>), which takes two arguments of type string as a function and returns a value of type bool. This coincides with the type of function required for the second argument of the code sort function above. Therefore, you can simply pass a greater than sign, and Swift can automatically infer that you want to use a string function that is greater than the number:
- var v1=copare (array,value:500,cb:>)
The following three points need to be noted in the use of closure expressions in Swift 1.2:
- Q There is a closure of a single return statement, which is now handled as a single-expression closure in type checking.
- Q The single expression, which is anonymous and contains a non-null return type, can now be used in the void context.
- The case of the closure type of the Q multi-expression may not be inferred by the type.
Swift2.0 language trailing closures
If the developer needs to pass a long closure expression as the last argument to the function, you can use the trailing closure, which can enhance the readability of the function. The general form of the trailing closure is as follows:
- Func somefunctionthattakesaclosure (Closure: ()) {
- function Body part
- }
- The following are not function calls using trailing closures
- Somefunctionthattakesaclosure ({
- Closure body part
- })
- The following are function calls made using trailing closures
- Somefunctionthattakesaclosure () {
- // Closure Body part
- }
Note: The trailing closure is a closure expression that is written after the function bracket, and the function supports calling it as the last argument. The code in example 7-30 can also be written as a trailing closure with the following code:
- Import Foundation
- Func Copare (ARR:[INT],VALUE:INT,CB: (num:int,value:int)->bool)->bool{
- For item in arr{
- if (CB (Num:item,value:value)) {
- return True
- }
- }
- return False
- }
- var array = [20,80,100,50,20]
- var v1=copare (array,value:500) {(num:int,value:int)->bool in
- Return Num>value
- }
- If V1==true {
- Print ("There are more than 500 elements in array arrays")
- }else{
- Print ("No more than 500 elements in array arrays")
- }
- ...
Trailing closures are typically used in code where closures are so long that they cannot be written on a single line. The following example uses the trailing closure to achieve the ability to change numbers to English. The code is as follows:
- Import Foundation
- Create a dictionary
- Let digitnames = [
- 0: "Zero", 1: "One", 2: "One", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
- ]
- Create an array
- Let numbers = [521,52,1,13,14]
- The following is a function call using trailing closures to convert the numbers to English
- Let strings = Numbers.map {
- (var number), String in
- var output = ""
- While number > 0 {
- Output = digitnames[number% 10]! + Output
- Number/= 10
- }
- Return output
- }
- Traverse and output
- For index in strings{
- Print (index)
- }
The results of the operation are as follows:
- Fivetwoone
- Fivetwo
- One
- Onethree
- Onefour
Note: the function map () is used in this code, and its function is to return a new sequence. Its grammatical form is as follows:
- Map (sequence, closure expression)
Where a closure expression is applied to all elements in a sequence, a new sequence is returned. But in this example, because the content in the closure is much more, it uses the form of a trailing closure.
Swift2.0 Language Capture values
Closures can capture constants or variables in the context in which they are defined. The following uses the Incrementor () function to capture values runningtotal and amount from the context. The code is as follows:
- Import Foundation
- Func makeincrementor (forincrement amount:int), Int {
- var runningtotal = 0
- Define the function Incrementor () to achieve the increase of runningtotal
- Func incrementor (), Int {
- RunningTotal + = Amount
- Return RunningTotal
- }
- Return Incrementor
- }
- Assign value
- var a = Makeincrementor (forincrement:10)
- Output
- Print ("Increment of output a")
- Print (A ())
- Print (A ())
- Print (A ())
- var B = Makeincrementor (Forincrement:5)
- Assignment, output
- Print ("Increment of output B")
- Print (b ())
- Print (b ())
- Print (b ())
The results of the operation are as follows:
- output a the Increment
- 10
- 20
- 30
- Output B the Increment
- 5
- 10
- 15
This article is selected from: Swift2.0 Language Quick Start v3.0 University bully Internal information, reproduced please indicate the source, respect the technology respect it people!
Closure of the Swift2.0 language tutorial