"Swift" Learning Notes (vii)--closures

Source: Internet
Author: User
Tags closure

1, what is the closure of the package

Closures are simply anonymous functions, lambdas functions , and the written point is that closures are self-contained function code blocks that can be passed and used in code to capture and store references to any constants and variables in the context in which they are located. This is called closed merge wrapped with these constants and variables, commonly known as closures.

2, closure of the form taken

In the previous function article, the global function is defined, and the inline function is actually a special form of closure.

    • A global function is a closed packet that has a name but does not capture any value
    • A nested function is a closure that has a name and can capture values within its enclosing function domain
    • A closure expression is an anonymous closure that uses lightweight syntax to capture variables or constant values in its context.

4. Global functions and nested functions are familiar, so look at the closure expression.

A closure expression is a way to construct an inline closure using concise syntax. It provides some syntax optimizations that make writing closures simple and straightforward. Below to analyze how it is simple and clear.

5, Example: Sorted function ( swift Standard library provides function will sort the values in an array of known types based on the closure function you provide for sorting based on the output type. Once the sort is complete, the function returns a new array with the same size as the original array, which contains the same type elements that have been sorted correctly. )

Let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

Func Backwards (s1:string, s2:string), Bool {    return s1 > S2}var reversed = sorted (names, backwards)//revers Ed for ["Ewa", "Daniella", "Chris", "Barry", "Alex")

sortedThe function needs to pass in two parameters:

    • Arrays of known types
    • The closure function, which needs to pass in two values that are the same as the array type, and returns a Boolean value to tell sorted the function whether the first parameter passed in after the sort end is preceded or followed by the second argument. If the first parameter value appears before the second parameter value, the sort closure function needs to be returned true , and vice versa false .
General expressions for closures

{(parameters)-ReturnType in    statements}

How can the call method above be optimized for what it looks like?

Reversed = sorted (names, {(s1:string, s2:string), Bool in    return s1 > s2})

In keyword, he indicates that the parameter and return value definitions are complete and the function body is about to begin.


Swift is a language determined by the parameter type, and it is also able to infer parameter types. So it can be written here.

Reversed = sorted (names, {s1, S2 in return s1 > s2})


For single-expression closures, you can also hide the return keyword.

Reversed = sorted (names, {s1, s2 in S1 > s2})

Swift automatically provides the parameter name abbreviation function for inline functions, which you can directly $0 , $1 , $2 to sequentially invoke the parameters of the closure.

Reversed = sorted (names, {$ > $})

You can also use the operator function

Reversed = sorted (names, >)

But there's so much to say. The readability is completely erased ...


If you need to enter a very long function body in a closure, it will be troublesome. It's inconvenient to read, so there's a trailing closure. The closure is placed on the tail of the function.


The above can be written as:

Reversed = sorted (names) {$ > $}


6. Value Capture

Closures can capture constants or variables in the context in which they are defined. Even though the original domain that defines these constants and variables does not already exist, closures can still reference and modify these values in the closure function body.

Func makeincrementor (forincrement amount:int), Int {    var runningtotal = 0    func incrementor (), Int {        RunningTotal + = Amount        return runningtotal    }    return Incrementor}

Through the front of the contact, the above function can understand ...

This function receives an INT parameter called Forincrement's external parameter name and returns a ()->int function type.

The parameter that does not receive runningtotal in the inline function can also be used, that is, the inline function captures the variables in the body of the function that contains it.


Closures are reference types





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Swift" Learning Notes (vii)--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.