The concept of closure (Closure) should not be unfamiliar to anyone who has not learned swift.
A friend who learns JavaScript should know that in JavaScript we often talk about closures, and many front-end engineers ask about closures.
So, what is a closure?
Let's look at the explanation of closures in javascript:
Closures is functions that has access to variables from another function ' s scope.
(This was often accomplished by creating a function inside a function.)
A closure is a function that can access variables within another function scope.
(This is usually done by declaring another function within a function)
It is not difficult to judge by the above definition that closures have the following two-point characteristics:
1. Closures are functions
2. Closures are functions inside a function
3. Closures can access variables of another function
Let's take a look at the example of javascipt closures:
functioncreatecomparisonfunction (PropertyName) {return function(Object1, object2) {varValue1 =Object1[propertyname]; varvalue2 =Object2[propertyname]; if(Value1 <value2) { return-1; } Else if(Value1 >value2) { return1; } Else { return0; } };}
Test code:
var compare = createcomparisonfunction ("name"); var result = Compare ({name: "Nicholas", age:35}, {name: "Greg", age:28// 1
As we can see in the JavaScript code above,
The Createcomparisonfunction function internally declares that the anonymous function can access the parameters of the Createcomparisonfunction function itself, which conforms to the definition of our closure.
Well, the closure in Swift is roughly similar, so let's look at the definition of closures in Swift:
Closures is discrete bundles of functionality that can is used in your application to accomplish specific tasks.
Closures are a set of functions that are used to accomplish certain tasks within your application that are unrelated to each other.
Read a bit of a mouthful, or let us use examples to speak, look at the following example:
Let's take a look at an example of an array sort that doesn't apply to closures
Import Cocoa // do not use closures var counts = [16229100 Bool { return i <= Counts.sort ( sortascending)
Now, let's look at the use of closure code to be more concise
Import Cocoa // use closure var counts = [16229 - = counts.sort ({ in return i < j})
Swift's closure syntax:
{(parameters), [return type] in
Code
}
The closure is made more concise by type inference (inference):
= [1622930 in i < J})
Make your code more concise with parameter placeholders:
= [16229 Counts.sort ({$0 < $1 })
It is not difficult to judge that the code above represents the first parameter, which is I, and that the first parameter is J.
Wow, the code is getting shorter, can it be shorter?
The answer is YES!
Remember the number of inline functions in C + + and we have it in swift!
Remove the brackets!
As a result, the code looks like this:
= [16229 Counts.sort {$0 < $1 }
Swift Language Essentials-closures (Closure)