Swift uses closure expressions and swift expressions

Source: Internet
Author: User

Swift uses closure expressions and swift expressions
The closure expressions in Swift are flexible. The standard syntax format is as follows:
{(Parameter list)-> return value type in
Statement Group
The parameter 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 provides a variety of closures to simplify writing. This section describes several different forms.
1. Simplified type inference
Type inference is Swift's strength. Swift can deduce the parameter type and return value type according to the context. The following code is a standard closure:
{(A: Int, B: Int)-> Int in
Return a + B
Swift can deduce that parameters a and B are of the Int type, and the return value is of the Int type. The simplified form is as follows:
{A, B in return a + B}
The modified sample code is as follows:

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 closure of the rows ① and ② In the above Code is a simplified method in the previous example, where a and B are parameters, and return is followed by the return value. How is it? Is it easy?
2. Hide the return keyword
If there is only one statement in the statement group inside the closure, such as return a + B, such statements are all return statements. The preceding keyword return can be omitted, in the following format:
{A, B in a + B}
The modified sample code is as follows:
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 return keyword of the closure of rows ① and ② Of the above Code is omitted. Note that only one return statement is included in the closure. The following statements are not allowed.
{A, B in var c; a + B}
3. abbreviated parameter name
The closure expression described in the previous section is very concise. However, the closure of Swift can be simplified. Swift provides the abbreviated parameter name function. We can use $0, $1, and $2 to call the parameters in the closure. $0 indicates the first parameter, and $1 indicates the second parameter, $2 refers to the third parameter, and so on $ n + 1 refers to the nth parameter.
You can also omit the definition of the parameter list in the closure. Swift can infer the types of these abbreviated parameters. The in keyword can also be omitted. The abbreviated parameter name is as follows:
{$0 + $1}
The sample code after the parameter name abbreviation is modified is as follows:
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 closure of the rows ① and ② Of the above Code uses the abbreviated parameter name.
4. return values using closures
Closure expressions are essentially function types and return values. We can directly use the closure return values in expressions. Modify the add and sub closures again. The sample code is as follows:
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 Code in line ① assigns values to c1, followed by a closure expression. However, the closure expression cannot be directly assigned to c1 because c1 is of the Int type and the return value of the closure is required. This requires a pair of parentheses () after the braces ending with the closure, and passing parameters for the closure through parentheses. The same is true for line 2 code. This method can be used to directly assign values to variables and constants, which is very convenient in some scenarios.

For more information, please refer to the first domestic Swift book "Swift development guide" for discussion. Website: http://www.51work6.com/swift.phpwelcome to the swifttechnology discussion group: 362298.pdf

Welcome to Zhijie iOS public classroom Platform

What is the use of javascript closures?

1. What is a closure?
The "official" explanation is: the so-called "closure" refers to an expression (usually a function) with many variables and an environment bound to these variables ), therefore, these variables are part of the expression.
I believe that few people can directly understand this sentence, because he described it too academic. I want to use how to create a closure in Javascript to tell you what a closure is, because it is very difficult to understand the definition of a closure directly by skipping the process of creating a closure. See the following code:
Function (){
Var I = 0;
Function B (){
Alert (++ I );
Return B;
Var c = ();
C ();
This code has two features:
1. function B is nested in function;
2. function a Returns function B.
In this way, after var c = a () is executed, variable c actually points to function B and then executes c () then a window will pop up showing the I value (the first time is 1 ). This Code actually creates a closure. Why? Because variable c outside function a references function B in function a, that is:

When function a's internal function B is referenced by a variable outside function a, a closure is created.

I guess you still don't understand the closure, because you don't know what the closure will do. Let's continue exploring it.

Ii. What is the function of closure?
In short, the function of the closure is that after a executes and returns, the closure makes the garbage collection mechanism of Javascript GC not to reclaim the resources occupied by, because the execution of the internal function B of a depends on the variables in. This is a straightforward description of the function of the closure, which is neither professional nor rigorous, but probably means that the process of understanding the closure needs to be gradual.
In the above example, because of the existence of the closure, the I in a always exists after function a returns, so that each execution of c (), I is the value of alert after auto-increment 1.

Then let's imagine another situation. If a does not return function B, the situation is completely different. Because after a is executed, B is not returned to the external world of a, but is referenced by a. At this time, a will only be referenced by B, therefore, functions a and B are referenced by each other without being disturbed by the outside world (referenced by the outside world), and functions a and B are recycled by GC. (The garbage collection mechanism of Javascript will be described in detail later)

3. microview of the world in the closure
If you want to have a better understanding of closures and the relationship between function a and nested function B, we need to introduce several other concepts: the function execution environment (excution context), the activity object (call object) scope and scope chain ). The process from definition to execution of function a is used as an example to describe these concepts.

1. When defining function a, the js interpreter sets the scope chain of function a to the "Environment" of function a when defining function ", if expression a is a global function, the scope chain contains only window objects.
2. When function a is executed, function a enters the corresponding execution environment (excution context ).
3. In the process of creating the execution environment, a scope attribute, that is, the scope of a, is added for a, and its value is the scope chain in step 1. That is, the scope chain of a. scope =.
4. A call object is created in the execution environment ). An activity object is also an object with attributes, but it does not have a prototype and cannot be directly accessed through JavaScript code. After creating the activity object, add the activity object to the top of the scope chain of. In this case, the scope chain of a contains two objects: The activity object of a and the window object.
5. The next step is to add an arguments attribute to the activity object, which stores the parameters passed when calling function.
6. Add the parameters of all function a and the reference of function B to the activity object of function. In this step, the definition of function B is completed. As in step 1, the scope chain of function B is set to the environment defined by B, that is, the scope of function.

At this point, the steps from definition to execution of function a are completed. In this case, a returns the reference of function B to function c,... the rest of the text>

JS closure concept

We should first explain the characteristics of the closure to better understand it.

Closure has two features:

1. As a reference to a function variable-when a function is returned, it is activated.
2. A closure is a stack that does not release resources when a function returns.

In fact, the above two points can be merged, that is, when the closure function returns, the internal variables of the function are activated, and the stack zone of the function is retained.

We are familiar with mainstream languages such as C and java. If the return function is executed inside the function, the function returns the result and deletes the region where the function is located in the memory. the lifecycle is stopped. this is also true for common js functions.
However, js functions with the closure feature are somewhat special.
For example:
Function (){
Var I = 0;
Function B (){
Alert (++ I );
Return B;
Var c = ();
C ();

This is a standard closure. In function a, function B is defined, and function a returns the value of function B.
Var c = ();
C ();
These two statements are very important.
When var c = a (); is executed, a must have passed the return statement. According to the function features of mainstream languages, the value of c is the return value of.
The second row of c () actually executes the B function. finally, no matter who executes the task, a window with a value of 0 will pop up. By now, all the lifecycles are ended theoretically.
However, if we execute one more row.
Var c = ();
C ();
C ();
0 is displayed for the first time, but 1 is displayed for the second execution.

That is to say, after c () for the first time, I in a is retained. Naturally, a is retained in the memory stack.

A is a return, but the and internal values still exist. This is the closure.

Okay. To sum up,
1. the outer layer of the closure is a function.
2. There are functions in the closure.
3. The closure will return the internal function.
4. The function returned by the closure cannot have return. (because this is the end)
5. After the closure is executed, the internal variables of the closure will exist, but the internal variables of the closure internal function will not exist.

Application scenarios of closures (HA, copying references)
1. Protect variable security in the function. Taking the initial example as an example, in function a, I can only access function B, but cannot access function B through other channels, thus protecting the security of I.
2. Maintain a variable in the memory. Still, for example, because of the closure, the I in function a is always in the memory, so each execution of c () will add 1 to the I self.

Based on the application scenarios of reference materials, we will naturally think of java or c ++ classes. Although JS does not have the concept of classes, it has similar execution results of classes.

There is also a controversial format:
(Function (a, B) (a, B );
If you have used jquery and observed its code, you may wonder how it is written. Someone on the Internet also calls this format a closure.

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.