Swift uses closure expressions

Source: Internet
Author: User



The closure expressions in Swift are flexible and have the following standard syntax format:
{(parameter list), return value type in
Statement Group
}
Where the argument list is the same as the parameter list in the function, the return value type is similar to the return value type in the function, but the difference is that the IN keyword is followed.
Swift offers a variety of closure simplification methods, which we will cover in several different forms.
1. Type inference Simplification
Type inference is the strength of swift, and swift can infer parameter types and return value types based on the context environment. The following code is a standard form of closure:
{(A:int, b:int), Int in
Return a + b
}
Swift can infer that the parameters A and B are of type int, and the return value is also of type int. The simplified form is as follows:
{A, B in return a + b}
The following example code is modified using this simplified method:


[HTML]View Plaincopy


func calculate (opr: String)-> (Int, Int)-> Int {
  
  
    var result: (Int, Int)-> Int
      
    switch (opr) {
    case "+":
        result = {a, b in return a + b} ①
    default:
        result = {a, b in return a-b} ②
    }
    return result;
}
  
  
let f1: (Int, Int)-> Int = calculate ("+")
println ("10 + 5 = \ (f1 (10,5))")
  
  
let f2: (Int, Int)-> Int = calculate ("-")
println ("10 + 5 = \ (f2 (10,5))")


The closures on lines ① and ② of the above code are simplified representations of the examples in the previous section, where a and b are parameters and return is followed by the return value. how about it? Is it simple?
2.Hide the return keyword
If there is only one statement in the closure statement group, such as return a + b, etc., then such statements are return statements. The previous keyword return can be omitted, the omitted form is as follows:
{a, b in a + b}
The modified sample code using this simplified approach is as follows:

[html] view plaincopy
func calculate (opr: String)-> (Int, Int)-> Int {
  
  
    var result: (Int, Int)-> Int
      
    switch (opr) {
    case "+":
        result = {a, b in return a + b} ①
    default:
        result = {a, b in return a-b} ②
    }
    return result;
}



The closure return keywords in line ① and line ② of the above code are omitted. It should be noted that the premise of omission is that there is only one return statement in the closure. Multiple statements like the following are not allowed.
{a, b in var c; a + b}
3. Abbreviated parameter name
The closure expressions introduced in the previous section are very concise, but Swift's closures can be simplified. Swift provides the parameter name abbreviation function. We can use $ 0, $ 1, $ 2 to indicate the parameters in the call closure, $ 0 refers to the first parameter, $ 1 refers to the second parameter, and $ 2 refers to the third parameter. Analogically $ n + 1 refers to the nth parameter.
Using parameter name abbreviations, you can also omit the definition of parameter lists in closures, and Swift can infer the types of these abbreviated parameters. In addition, the in keyword can be omitted. The parameter name is abbreviated as follows:
{$ 0 + $ 1}
The modified sample code using the parameter name abbreviation is as follows:

[html] view plaincopy
func calculate (opr: String)-> (Int, Int)-> Int {
  
  
    var result: (Int, Int)-> Int
      
    switch (opr) {
    case "+":
        result = {$ 0 + $ 1} ①
    default:
        result = {$ 0-$ 1} ②
    }
    return result;
}
  
  
let f1: (Int, Int)-> Int = calculate ("+")
println ("10 + 5 = \ (f1 (10,5))")
  
  
let f2: (Int, Int)-> Int = calculate ("-")
println ("10 + 5 = \ (f2 (10,5))")


The closures on lines ① and ② of the above code use parameter name abbreviations.
4. Use closures to return values
Closure expressions are essentially function types and have return values. We can directly use the return value of a closure in an expression. Modify the add and sub closures again. The sample code is as follows:

[html] view plaincopy
let c1: Int = ((a: Int, b: Int)-> Int in
                return a + b
          } (10,5) ①
  
  
println ("10 + 5 = \ (c1)")
  
  
let c2: Int = ((a: Int, b: Int)-> Int in
                    return a-b
                } (10,5) ②
  
  
println ("10-5 = \ (c2)")



The above code has two expressions. The first line of code assigns a value to c1, followed by a closure expression. However, the closure expression cannot be directly assigned to c1, because c1 is of type Int, and the return value of the closure is required. This requires a pair of parentheses (10,5) after the brace at the end of the closure, and the parameters are passed to the closure through the parentheses (10,5). The same is true for line ②. In this way, you can directly assign values to variables and constants, which is very convenient in some scenarios.

 

 

For more content, please pay attention to the first domestic Swift book "Swift Development Guide".
 

 

 Closure expressions in Swift are flexible, and their standard syntax is as follows:
{(Parameter list)-> return value type in
    Statement group
}
Among them, the parameter list has the same form as the parameter list in the function, and the return value type is similar to the return value type in the function, except that the in keyword follows.
Swift provides a variety of closure simplifications. In this section we will introduce several different forms.
1. Type inference simplification
Type inference is Swift's strong point. Swift can infer parameter types and return value types based on the context. The following code is a standard form of closure:
((a: Int, b: Int)-> Int in
    return a + b
}
Swift can infer that the parameters a and b are of type Int, and the return value is also of type Int. The simplified form is as follows:
{a, b in return a + b}
The modified sample code using this simplified approach is as follows:

[html] view plaincopy
func calculate (opr: String)-> (Int, Int)-> Int {
  
  
    var result: (Int, Int)-> Int
      
    switch (opr) {
    case "+":
        result = {a, b in return a + b} ①
    default:
        result = {a, b in return a-b} ②
    }
    return result;
}
  
  
let f1: (Int, Int)-> Int = calculate ("+")
println ("10 + 5 = \ (f1 (10,5))")
  
  
let f2: (Int, Int)-> Int = calculate ("-")
println ("10 + 5 = \ (f2 (10,5))")


The closures on lines ① and ② of the above code are simplified expressions of the example in the previous section, where a and b are parameters, and return is followed by the return value. how about it? Is it simple?
2.Hide the return keyword
If there is only one statement in the closure statement group, such as return a + b, etc., then such statements are return statements. The previous keyword return can be omitted, and the omitted form is as follows:
{a, b in a + b}
The modified sample code using this simplified approach is as follows:

[html] view plaincopy
func calculate (opr: String)-> (Int, Int)-> Int {
  
  
    var result: (Int, Int)-> Int
      
    switch (opr) {
    case "+":
        result = {a, b in return a + b} ①
    default:
        result = {a, b in return a-b} ②
    }
    return result;
}



The closure return keywords in lines ① and ② of the above code are omitted. It should be noted that the premise of omission is that there is only one return statement in the closure. Multiple statements like the following are not allowed.
{a, b in var c; a + b}
3. Abbreviated parameter name
The closure expressions introduced in the previous section are very concise, but Swift's closures can be simplified. Swift provides the parameter name abbreviation function. We can use $ 0, $ 1, $ 2 to indicate the parameters in the call closure, $ 0 refers to the first parameter, $ 1 refers to the second parameter, and $ 2 refers to the third parameter. Analogically $ n + 1 refers to the nth parameter.
Using parameter name abbreviations, you can also omit the definition of parameter lists in closures, and Swift can infer the types of these abbreviated parameters. In addition, the in keyword can be omitted. The parameter name is abbreviated as follows:
{$ 0 + $ 1}
The modified sample code using the parameter name abbreviation is as follows:

[html] view plaincopy
func calculate (opr: String)-> (Int, Int)-> Int {
  
  
    var result: (Int, Int)-> Int
      
    switch (opr) {
    case "+":
        result = {$ 0 + $ 1} ①
    default:
        result = {$ 0-$ 1} ②
    }
    return result;
}
  
  
let f1: (Int, Int)-> Int = calculate ("+")
println ("10 + 5 = \ (f1 (10,5))")
  
  
let f2: (Int, Int)-> Int = calculate ("-")
println ("10 + 5 = \ (f2 (10,5))")


The closures on lines ① and ② of the above code use parameter name abbreviations.
4. Use closures to return values
Closure expressions are essentially function types and have return values. We can directly use the return value of a closure in an expression. Modify the add and sub closures again. The sample code is as follows:

[html] view plaincopy
let c1: Int = ((a: Int, b: Int)-> Int in
                return a + b
          } (10,5) ①
  
  
println ("10 + 5 = \ (c1)")
  
  
let c2: Int = ((a: Int, b: Int)-> Int in
                    return a-b
                } (10,5) ②
  
  
println ("10-5 = \ (c2)")



The above code has two expressions. The first line of code assigns a value to c1, followed by a closure expression. However, the closure expression cannot be directly assigned to c1, because c1 is of type Int, and the return value of the closure is required. This requires a pair of parentheses (10,5) after the brace at the end of the closure.
Number (10,5) passes parameters for the closure. The same is true for line ②. In this way, you can directly assign values to variables and constants, which is very convenient in some scenarios.

 

 

For more content, please pay attention to the first domestic Swift book "Swift Development Guide". The book discussion website: http://www.51work6.com/swift.php Welcome to the Swift technical discussion group: 362298485
  Follow Zhijie iOS Classroom Public Platform

Swift uses closure expressions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.