內(nèi)嵌函數(shù)
let names = ["Chris","Alex","Ewa","Barry","Daniella"]
func backward(_ s1: String, _ s2: String) -> Bool {
return s1 > s2
}
var reversedNames = names.sorted(by: backward)
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
閉包表達式語法
{ (parameters) -> (return type) in
statements
}
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1 > s2
})
// 因排序閉包為實際參數(shù)來傳遞給函數(shù),故 Swift 能推斷它的形式參數(shù)類型和返回類型
// 因為所有的類型都能被推斷,返回箭頭 ( ->) 和圍繞在形式參數(shù)名周圍的括號也能被省略
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
// 從單表達式閉包隱式返回,單表達式閉包能夠通過從它們的聲明中刪掉 return 關(guān)鍵字來隱式返回它們單個表達式的結(jié)果
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
// 簡寫的實際參數(shù)名
reversedNames = names.sorted(by: { $0 > $1 } )
// 運算符函數(shù)
reversedNames = names.sorted(by: >)
尾隨閉包
//如果你需要將一個很長的閉包表達式作為函數(shù)最后一個實際參數(shù)傳遞給函數(shù),使用尾隨閉包將增強函數(shù)的可讀性
func someFunctionThatTakesAClosure(closure:() -> Void){
//function body goes here
}
//here's how you call this function without using a trailing closure
someFunctionThatTakesAClosure({
//closure's body goes here
})
//here's how you call this function with a trailing closure instead
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
//eg:
reversedNames = names.sorted() { $0 > $1 }
//如果閉包表達式作為函數(shù)的唯一實際參數(shù)傳入,而你又使用了尾隨閉包的語法,那你就不需要在函數(shù)名后邊寫圓括號了:
reversedNames = names.sorted { $0 > $1 }
// 當閉包很長以至于不能被寫成一行時尾隨閉包就顯得非常有用了
// eg:
let digitNames = [
0: "Zero",1: "One",2: "Two", 3: "Three",4: "Four",
5: "Five",6: "Six",7: "Seven",8: "Eight",9: "Nine"
]
let numbers = [16,58,510]
let strings = numbers.map {
(number) -> String in
var number = number
var output = ""
repeat {
output = digitNames[number % 10]! + output
number /= 10
} while number > 0
return output
}
// strings is inferred to be of type [String]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]
捕獲值
//內(nèi)嵌函數(shù)
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incremented
}
//調(diào)用
let incrementByTen = makeIncrementer(forIncrement: 10)
incrementByTen()
//return a value of 10
incrementByTen()
//return a value of 20
incrementByTen()
//return a value of 30
/**如果你建立了第二個 incrementer ,它將會有一個新的、獨立的 runningTotal 變量的引用*/
let incrementBySeven = makeIncrementer(forIncrement: 7)
incrementBySeven()
// returns a value of 7
/**
* 再次調(diào)用原來增量器 ( incrementByTen ) 繼續(xù)增加它自己的變量 runningTotal 的值,并且不會影響 incrementBySeven 捕獲的變量 runningTotal 值
*/
incremByTen()
//returns a value of 40
閉包是引用類型
//無論你什么時候安賦值一個函數(shù)或者閉包給常量或者變量,你實際上都是將常量和變量設(shè)置為對函數(shù)和閉包的引用。這上面這個例子中,閉包選擇 incrementByTen 指向一個常量,而不是閉包它自身的內(nèi)容。
這也意味著你賦值一個閉包到兩個不同的常量或變量中,這兩個常量或變量都將指向相同的閉包:
let alsoIncrementByTen = incrementByTen
alsoIncrementByTen()
//return a value of 50
逃逸閉包 (@escaping )
//當閉包作為一個實際參數(shù)傳遞給一個函數(shù)的時候,我們就說這個閉包逃逸了,因為它可以在函數(shù)返回之后被調(diào)用。當你聲明一個接受閉包作為形式參數(shù)的函數(shù)時,你可以在形式參數(shù)前寫 @escaping 來明確閉包是允許逃逸的。
var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
completionHandlers.append(completionHandler)
}
func someFunctionWithNonescapingClosure(closure: () -> Void) {
closure()
}
// 逃逸閉包:閉包可以逃逸的一種方法是被儲存在定義于函數(shù)外的變量里
// 非逃逸:僅調(diào)用一次
class SomeClass {
var x = 10
func doSomething() {
someFunctionWithEscapingClosure { self.x = 100 }
someFunctionWithNonescapingClosure { x = 200 }
}
}
let instance = SomeClass()
instance.doSomething()
print(instance.x)
// Prints "200"
completionHandlers.first?()
print(instance.x)
// Prints "100"
自動閉包(匿名block?)
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
print(customersInLine.count)
// prints "5"
let customerProvider = { customersInLine.removeAtIndex(0) }
print(customersInLine.count)
// prints "5"
print("Now serving \(customerProvider())!")
// prints "Now serving Chris!"
print(customersInLine.count)
// prints "4"
對比一下使用自動閉包的區(qū)別
//傳一個閉包作為實際參數(shù)到函數(shù)的時候,你會得到與延遲處理相同的行為。
// customersInLine is ["Alex", "Ewa", "Barry", "Daniella"]
func serve(customer customerProvider: () -> String) {
print("Now serving \(customerProvider())!")
}
serve(customer: { customersInLine.remove(at: 0) } )
// Prints "Now serving Alex!"
// customersInLine is ["Ewa", "Barry", "Daniella"]
func serve(customer customerProvider: @autoclosure () -> String) {
print("Now serving \(customerProvider())!")
}
serve(customer: customersInLine.remove(at: 0))
// Prints "Now serving Ewa!"
// 如果你想要自動閉包允許逃逸,就同時使用 @autoclosure 和 @escaping 標志。
// customersInLine is ["Barry", "Daniella"]
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.")
// Prints "Collected 2 closures."
for customerProvider in customerProviders {
print("Now serving \(customerProvider())!")
}
// Prints "Now serving Barry!"
// Prints "Now serving Daniella!"