Closure of Swift Learning notes

Source: Internet
Author: User
Tags closure

Introduction (really very simple)

The complete shape of the closure is this way:

    (parameters) -> returnType in        statements    }

This is how it is written in one line:

    {(parameters) -> (returnType) in statements}
Form

Closures exist in three forms:

1.全局的函数都是闭包,它们有自己的名字,但是没有捕获任何值。2.内嵌的函数都是闭包,它们有自己的名字,而且从包含他们的函数里捕获值。3.闭包表达式都是闭包,它们没有自己的名字,通过轻量级的语法定义并且可以从上下文中捕获值。
Capturing values

A closure can capture the value of a context and then store it. As for whether a reference or a copy is stored, Swift determines whether to capture the reference or copy the value and also handles the memory management of the variable.

The following example can illustrate many problems:

Func Makeincrementor(Forincrement amount:int)(), Int {var runningtotal =0 Func Incrementor(), Int {runningtotal + = AmountReturn RunningTotal}return Incrementor} let Incrementbyten = Makeincrementor (forIncrement: 10) Incrementbyten () //runningtotal = 10 Incrementbyten () //runningtotal = 20 incrementByTen () //runningtotal = 30 let incrementByTen2 = Makeincrementor (forincrement: 10) incrementByTen2 () //runningtotal = 10 let IncrementByTen3 = Incrementbyten Incrementbyten () //runningtotal = 40   

Because incrementByTen2 a completely new closure is declared, runningTotal there is no continuation of the above count. incrementByTen3and the incrementByTen same closure as the point, so runningTotal the value is cumulative.

Parameter abbreviations

We can use $0 $1 $2 this directly to define the parameters of the closure in turn. For example sorted , a function:

    var reversed = sorted(["c","a","d","b"], { $0 > $1 }) // d c b a
Trailing closures

I have always felt that the closure of the last one is }) very difficult to see, in JS everywhere in this situation. If the closure is the last parameter of the function, Swift provides a trailing closure (Trailing Closures) to solve this aesthetic problem:

    // 以下是不使用尾随闭包进行函数调用    someFunc({        // 闭包主体部分    })    // 以下是使用尾随闭包进行函数调用    someFunc() {      // 闭包主体部分 }

Ok so the front of that sort can be rewritten with trailing closures:

    var reversed = sorted(["c","a","d","b"]) { $0 > $1 } // d c b a

If there are no other parameters besides closures, you can even remove the parentheses.

Do you remember what we wrote in front of us? map reduce filter Use trailing closures to make them look better. For example, the previous one to select a number greater than 30 filter can be written like this:

    var oldArray = [10,20,45,32] var filteredArray = oldArray.filter{ return $0 > 30 } println(filteredArray) // [45, 32]
Deformation

Transformers God Horse is the most love. A summary closure of the deformation is roughly the following patterns:

[1,2,3].map ({(i:int)->Int in return i * 2}) [1, 2, 3].mapin return I * Span class= "Hljs-number" >2}) [1, 2, 3]. map ({i in I * 2}) [1, 2, 3]. map ({$0 * 2}) [1, 2, 3]. map () {$0 * 2} [1, 2, 3].map {$0 * 2}          
Contrast

The animateWithDuration block and the closure are compared in a simple way by UIView.

block 版本: [UIView animateWithDuration:1 animations:^{ // DO SOMETHING } completion:^(BOOL finished) { NSLog(@"OVER"); }];closure 版本: UIView.animateWithDuration(1, animations: { () in // DO SOMETHING }, completion:{(Bool) in println("OVER") })

can see the original^The symbol no longer exists and is replaced by the argument and the return value.in. Note that if there isin, even if there are no parameters, the return value must be(), or you will get an error.
Summarize

Like Objective-c's Fuckingblock, Swift came out and Fuckingclosure was born. Summarizes the common syntax and format of Closure:

    As a variableVarClosurename:(parametertypes) (returntype)As a variable of an optional typeVarClosurename:((parametertypes) (returntype))? As an alias.TypealiasClosuretype =(parametertypes) (returntype)Func as the parameter of the function({(parametertypes)-(ReturnType)In statements})//As a function parameterArray.Sort({(Item1:int, item2:int), BoolInchReturn item1 < ITEM2})//As parameter of function-implied parameter typeArray.Sort({(item1, item2), BoolInchReturn item1 < ITEM2})//As a function parameter-implied return typeArray.Sort ({(item1, item2) in return item1 < item2})//As a function parameter-trailing closure array. Sort { (item1, item2) in return item1 < item2}//As parameters of the function-parameter array.< by number Span class= "Hljs-title" >sort {return $0 < $1}//As parameter of function-trailing closure and implied return type array. Sort {$0 < $1}//As arguments to functions-reference existing functions sort (<)         
References
    • Closures
    • Closure Expressions in Swift
    • Fucking Closure
    • Writing completion blocks with closures in Swift
    • Enough about Swift Closures to choke a Horse
    • Functions and Closures in Swift
    • Swift how-to:writing Trailing Closures

Knowledge Source: http://lib.csdn.net/article/swift/474

Closure of Swift Learning notes

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.