// ## 尾随闭包
func someFunctionThatTakesAClosure(closure: () -> Void) {
// 函数体部分
}
someFunctionThatTakesAClosure(closure: {
})
someFunctionThatTakesAClosure {
}
// ## 值捕获
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
let incrementByTen = makeIncrementer(forIncrement: 10)
var d = incrementByTen() //10
d = incrementByTen() //20
d = incrementByTen() //30
let incrementBySeven = makeIncrementer(forIncrement: 7)
d = incrementBySeven() //7
d = incrementByTen() //40
let alsoIncrementByTen = incrementByTen
alsoIncrementByTen() //50
// ## 逃逸闭包
//一种能使闭包“逃逸”出函数的方法是,将这个闭包保存在一个函数外部定义的变量中
var completionHandlers: [ ()->Void ] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping ()->Void) {
completionHandlers.append(completionHandler)
}
//将一个闭包标记为 @escaping 意味着你必须在闭包中显式地引用 self。
func someFunctionWithNonescapingClosure(closure: () -> Void) {
closure()
}
class SomeClass {
var x = 10
func doSomething() {
someFunctionWithEscapingClosure {
self.x = 100
}
someFunctionWithNonescapingClosure { x = 200 }
}
}
let instance = SomeClass()
instance.doSomething()
print(instance.x)
// 打印出“200”
completionHandlers.first?()
print(instance.x)
// 打印出“100”
// ## 自动闭包让你能够延迟求值,因为直到你调用这个闭包,代码段才会被执行
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
print(customersInLine.count)
// 打印出“5”
let customerProvider = { customersInLine.remove(at: 0) }
print(customersInLine.count)
// 打印出“5”
print("现在才移除第一个元素 \(customerProvider())")
// 现在才移除第一个元素 Chris
print(customersInLine.count)
// 打印出“4”
//将闭包作为参数传递给函数时,你能获得同样的延时求值行为。
func serve(customer customerProvider: ()->String) {
print("函数被调用时才移除第一个元素 \(customerProvider())")
}
serve(customer: { customersInLine.remove(at: 0) })
//通过将参数标记为 @autoclosure 来接收一个自动闭包
func serve(customer customerProvider: @autoclosure () -> String) {
print("Now serving \(customerProvider())!")
}
serve(customer: customersInLine.remove(at: 0))
// 打印“Now serving Ewa!”
// ## 自动闭包和逃逸闭包
var customerProviders: [ () -> String] = []
func collectCustomerProviders(_ customerProvider: @autoclosure @escaping () -> String) {
customerProviders.append(customerProvider)
}
collectCustomerProviders(customersInLine.remove(at: 0))
collectCustomerProviders(customersInLine.remove(at: 0))
print("Collected \(customerProviders.count) closures")// 打印“Collected 2 closures.”
for customerProvider in customerProviders {
print("Now serving \(customerProvider())!")
}
// 打印“Now serving Barry!”
// 打印“Now serving Daniella!”
Swift8 - 闭包
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...