1.有三种closures:全局函数,嵌套函数,代码块。前两种是有名字的,后一种是无名字的。当一个函数用函数来做为arguments时,无名closure就很有用了。你不需要另外定义一个函数指针,只要在函数调用表达式的参数列表里直接写一个函数。唔,很难说这是个好主意,当然终归有用的着的场合。
-
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
-
func backwards(s1: String, _ s2: String) -> Bool {
-
return s1 > s2
-
}
-
var reversed = names.sort(backwards)
-
var reversed = names.sort( { (s1: String, s2: String) -> Bool in return s1 > s2 } )
-
var reversed = names.sort( { s1, s2 in return s1 > s2 } )
-
var reversed = names.sort( { s1, s2 in s1 > s2 } )
-
var reversed = names.sort( { $0 > $1 } )
-
var reversed = names.sort(>)
-
var reversed = names.sort() { $0 > $1 }
-
var reversed = names.sort { $0 > $1 }
reversed 前面加个var表示接下来这几条语句是等价的,并且不会同时存在一个程序中。
2.
-
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
-
var runningTotal = 0
-
func incrementer() -> Int {
-
runningTotal += amount
-
return runningTotal
-
}
-
return incrementer
-
}
-
-
let incrementByTen = makeIncrementer(forIncrement: 10)
-
incrementByTen() // returns a value of 10
-
incrementByTen() // returns a value of 20
-
incrementByTen() // returns a value of 30
-
-
let incrementBySeven = makeIncrementer(forIncrement: 7)
-
incrementBySeven() // returns a value of 7
-
-
incrementByTen() // returns a value of 40
incrementer()不带参数,然而它引用了 runningTotal和amount.这就叫做 capturing by reference. Capturing by reference确保runningTotal and amount 在结束对makeIncrementer的调用后不会消失,并且保证下次调用incrementer时runningTotal还在。换句话说,makeIncrementer
返回之后runningTotal和amount已经属于返回的incrementer(),而incrementByTen和incrementBySeven是两个独立的变量,归属于这两个变量的两组(runningTotal,amount)是不相干的。
需要注意这种情况
-
let alsoIncrementByTen = incrementByTen
-
alsoIncrementByTen() // returns a value of 50
3.
-
func someFunctionWithNoescapeClosure(@noescape closure: () -> Void) {
-
closure()
-
}
-
var completionHandlers: [() -> Void] = []
-
func someFunctionWithEscapingClosure(completionHandler: () -> Void) {
-
completionHandlers.append(completionHandler)
-
}
-
-
class SomeClass {
-
var x = 10
-
func doSomething() {
-
someFunctionWithEscapingClosure { self.x = 100 }
-
someFunctionWithNoescapeClosure { x = 200 }
-
}
-
}
-
-
let instance = SomeClass()
-
instance.doSomething() //给x赋了两次值,100然后200
-
print(instance.x) // prints "200" 第二次赋的值
-
completionHandlers.first?() //给x重新赋了一次值,因为保留了对instance的引用
-
print(instance.x) // prints "100"
阅读(803) | 评论(0) | 转发(0) |