[Swift] Day08: getting started with closures, swiftday08
Getting started with closures
Just as I got back from Shanghai today, let's simply list some content.
Introduction (really simple)
The complete form of the closure is like this:
{ (parameters) -> returnType in statements}Abbreviated parameter name
We can directly use$0 $1 $2In this way, the closure parameters are defined in sequence. For examplesortedFunction:
var reversed = sorted(["c","a","d","b"], { $0 > $1 }) // d c b aTrailing Closure
I always think the last part of the Closure})It's hard to see. This can be seen everywhere in JS. Swift provides trailing closures to solve this aesthetic problem:
// The following code does not use the trailing closure for function call someFunc ({// closure body part}) // the following code uses the trailing closure for function call someFunc () {// closure body part}
OK. The preceding sorting can be rewritten using the trailing closure as follows:
var reversed = sorted(["c","a","d","b"]) { $0 > $1 } // d c b a
Remember what we wrote earliermap,reduce,filterIs Sanyuan a general? Using trailing closures can make them look better. For example, the preceding one selects a number greater than 30.filterYou can write it like this:
var oldArray = [10,20,45,32]var filteredArray = oldArray.filter{ return $0 > 30}println(filteredArray) // [45, 32]Capture value
Closure can capture the context value and store it. As for whether to store references or copies, Swift will decide whether to capture references or copy values, and also process the memory management operations of variables.
The following example illustrates many problems:
func makeIncrementor(forIncrement amount: Int) -> () -> Int { var runningTotal = 0 func incrementor() -> Int { runningTotal += amount return runningTotal } return incrementor}let incrementByTen = makeIncrementor(forIncrement: 10)incrementByTen() // runningTotal = 10incrementByTen() // runningTotal = 20incrementByTen() // runningTotal = 30let incrementByTen2 = makeIncrementor(forIncrement: 10)incrementByTen2() // runningTotal = 10let incrementByTen3 = incrementByTenincrementByTen() // runningTotal = 40
BecauseincrementByTen2Declared a brand new closure, sorunningTotalThe above count is not continued. WhileincrementByTen3AndincrementByTenPoint to the same closure, sorunningTotalIs accumulated.
References