Swift Learning: Closures (Closures)

Source: Internet
Author: User
Tags closure

/* Closures (Closures)
* Closures are self-contained functional code blocks that can be used in code or used as parameters to pass values.
* Closures in Swift are similar to the lambdas in C, OC, and other programming languages such as Python (blocks).
* Closures can capture and store references to any constants and variables defined in the context. This is called the self-containment of variables and variables,
* Hence the name "closure" ("Closures)"). Swift also handles memory management for all captured references.
*
* Global functions and nested functions are really special closures.
* Closures in the form of:
* (1) Global functions are closures, have names but cannot capture any values.
* (2) Nested functions are closures and have names that can also capture values within the enclosing function.
* (3) The closure expressions are anonymous closures, which use lightweight syntax to capture values based on the context environment.
*
* Closures in Swift have a lot of optimizations in place:
* (1) Infer parameters and return value types based on context
* (2) Implicit return from a single-line expression closure (that is, the closure body has only one line of code, you can omit return)
* (3) You can use simplified parameter names, such as $ A, $ (starting from 0, representing the I parameter ...)
* (4) provides trailing closure syntax (Trailing closure syntax)
*/

Use the Sort method in the swift standard library to simplify closures in a step-by-step manner
The sort function requires two parameters
Parameter one: array
Parameter two: A closure: With two parameters, these two parameter types are the same as the element type in the array, the return value is bool
var names = ["Swift", "Arial", "Soga", "Donary"]

The first way: using functions
Func Backwards (firststring:string, secondstring:string), Bool {
return firststring > secondstring//Ascending sort
}
Here's the second argument, a function is passed
Reversed is equal to ["Swift", "Soga", "Donary", "Arial"]
var reversed = sort (nams, backwards)

The second way: using closures
The complete closure is written in curly braces with a parameter list and a return value, using the keyword in to indicate the beginning of the closure body
(firststring:string, secondstring:string) closure parameter list
-BOOL indicates that the closure return value type is bool
The In keyword indicates the beginning of the closure body
Reversed = sort (names, {(firststring:string, secondstring:string), Bool in
return firststring > Secondstring
})

This can be further simplified because the closure code is shorter and can be written on one line
Reversed = sort (names, {(firststring:string, secondstring:string), Bool in return firststring > secondstring})

Here's a further simplification: automatically infer types based on environment context
The argument list does not indicate a type, nor does it indicate a return value type, because Swift can be extrapolated from context
The type of firststring and secondstring will be the type of the names array element, and the return value type will be based on the return statement result
Reversed = sort (names, {firststring, secondstring in return firststring > secondstring})

Further simplification: implicit return (single-line statement closure)
Because the closure body has only one line of code, you can omit return
Reversed = sort (names, {firststring, secondstring in Firststring > secondstring})

Further simplification: Using simplified parameter names ($i, i=0,1,2 ... Starting from 0)
Swift infers that a closure requires two parameters, the same type as the names array element
Reversed = sort (names, {$ > $})

The simplest way to do this: using Operators
Reversed = sort (names, >)

/*
* Trailing closures (Trailing Closures)
* If the function requires a closure parameter as a parameter, and this parameter is the last parameter, and the closure expression is very long,
* It is useful to use trailing closures. Trailing closures can be placed outside the function argument list, which is outside the brackets. If the function has only one argument,
* Then you can omit the brackets () and follow the closures directly.
*/
The array method map () requires a closure as a parameter
Let strings = Numbers.map {///Map function after () can be omitted
(var number), String in
var output = ""
While number > 0 {
Output = String (number%) + output
Number/= 10
}
Return output
}

/* Capture Value
* Closures can be captured to defined constants and variables according to the environment context. Closures can reference and modify these captured constants and variables,
* Even if defined as a constant in the original scope or the variable no longer exists (very good).
* The simplest form of closure in Swift is a nested function.
*/
Func increment (#amount: int), ((), int) {
var total = 0
Func Incrementamount (), Int {
Total + = amount//Total is a variable in the body of an external function, which can be captured
Return Total
}
return Incrementamount//Returns a nested function (closure)
}

Closures are reference types, so incrementbyten declarations as constants can also modify total
Let Incrementbyten = Increment (amount:10)
Incrementbyten ()//Return 10,incrementbyten is a closed package
Here is no change to the increment reference, so the previous value will be saved
Incrementbyten ()//Return 20
Incrementbyten ()//Return 30

Let Incrementbyone = Increment (amount:1)
Incrementbyone ()//return 1
Incrementbyone ()//return 2
Incrementbyten ()//Return 40
Incrementbyone ()//Return 3

Swift Learning: Closures (Closures)

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.