1.什麼是閉包(Closure)? 閉包是一個完整的設計功能模塊,可以在代碼中傳遞和使用,類似於Object-C的block(但是還是有區別,下麵會說明)或者其他語言的匿名函數(lambdas)。閉包可以捕獲或者儲存它們所在上下文的常量和變數。在Swift里等價於函數,是一等公民。 閉包有三種形式: ...
1.什麼是閉包(Closure)?
閉包是一個完整的設計功能模塊,可以在代碼中傳遞和使用,類似於Object-C的block(但是還是有區別,下麵會說明)或者其他語言的匿名函數(lambdas)。閉包可以捕獲或者儲存它們所在上下文的常量和變數。在Swift里等價於函數,是一等公民。
閉包有三種形式:
- 全局函數,有名字的閉包並且不捕獲任何值(定義的一般函數)
- 嵌套函數,有名字的閉包,可以在閉包所在函數內部捕獲值(函數里嵌套函數)
- 閉包表達式,沒有名字的閉包,使用簡潔的語法,可以在包裹閉包的上下文捕獲值(閉包)
舉例說明:
//Global function
func block() {
print("block") //block
}
//Nested function
func block(){
let name = "block"
func printStr() {
print(name)
}
printStr()
}
block() //block
//Closure expression
let block = {
print("block")
}
block() //block
swift對閉包的表達式做了相關的優化:
- 從上下文推斷傳入參數和返回值
- 單一表表達式閉包的隱式返回
- 簡短的參數名
- 尾隨閉包
舉例說明:
let numbers = [1, 3, 2, 4, 7, 8, 5]
let sortedNums = numbers.sorted { (a: Int, b: Int) -> Bool in
return a > b
}
//下麵常量返回的都是[8, 7, 5, 4, 3, 2, 1]
//從上下文推斷傳入參數和返回值
let sortedNums2 = numbers.sorted { (a, b) in
return a > b
}
//單一表表達式閉包的隱式返回
let sortedNums = numbers.sorted { $0 > $1 }
//簡短的參數名
let sortedNums2 = numbers.sorted { (a, b) in
return a > b
}
//尾隨閉包
let sortedNums = numbers.sorted { $0 > $1 }
2.閉包的表達式語法(Closure Expressions)
定義:
{(parameters) -> return type in
statements
}
舉一些例子:
//沒有參數和返回值的block定義
let noParameterAndNoReturnValue: () -> () = {
print("Hello world!")
}
//沒有參數,有返回值的block定義
let noParameterAndReturnValue: () -> (Int) = {
return 5
}
//有一個參數和返回值的block定義
let oneParameterAndNoReturnValue: (Int) -> (Int) = { x in
return x + 2
}
//有多個參數和返回值的block定義
let mutipleParameterAndNoReturnValue: (Int, Int) -> (Int) = { (x, y) in
return x + y
}
3.簡短的參數名字(Shorthand argument syntax)
swift支持類型推斷,什麼意思呢?就是閉包的參數和返回類型都可以交給編譯器去推斷,在編碼階段就可以省略。閉包裡面$0,$1代表的是傳入的第一個參數和第二個參數,下麵看代碼:
//$0代表第一個參數,$1代表第二個參數,語法非常簡潔
let numbers = [1, 3, 2, 4, 7, 8, 5]
let sortedNums = numbers.sorted { $0 > $1 } //[8, 7, 5, 4, 3, 2, 1]
順便提一下函數(閉包)參數省略的過程,還是以數組降序為例:
let numbers = [1, 3, 2, 4, 7, 8, 5]
let sortedNums = numbers.sorted { (a: Int, b: Int) -> Bool in
return a > b
} //[8, 7, 5, 4, 3, 2, 1]
如果一個函數的返回類型和參數類型可以推導出來,則返回類型和參數類型都可以省略。刪除:Int,-> Bool,上面的表達式變成:
let numbers = [1, 3, 2, 4, 7, 8, 5]
let sortedNums = numbers.sorted { (a, b) in
return a > b
} //[8, 7, 5, 4, 3, 2, 1]
如果參數的個數可以推導出來,則參數可以省略,使用$0,$1的方式代表參數。參數省略了,in關鍵字在這裡就沒有意義了,也可以省略,則上面的表達式變成:
let numbers = [1, 3, 2, 4, 7, 8, 5]
let sortedNums = numbers.sorted {
return $0 > $1
} //[8, 7, 5, 4, 3, 2, 1]
在swift里,如果函數體只有一行,則可以把return關鍵字省略,單一表達式閉包隱式返回,則代碼進一步演變成:
let numbers = [1, 3, 2, 4, 7, 8, 5]
let sortedNums = numbers.sorted {
$0 > $1
} //[8, 7, 5, 4, 3, 2, 1]
最後,還能更近一步簡化。可能很多人都鬱悶了,就剩兩個參數和操作符了,還能怎麼簡化?別急,swift裡面還有一個簡化規則,因為<也是函數,並且和函數sorted函數接收的參數個數,類型和返回值都一樣,所以,能推導出來的東西都能簡化,那麼,更暴力的簡化來了:
let numbers = [1, 3, 2, 4, 7, 8, 5]
let sortedNums = numbers.sorted (by: > ) //[8, 7, 5, 4, 3, 2, 1]
看出來什麼了沒有?沒錯,這裡的簡化不是放在閉包裡面的。我的理解是,整個閉包等價於>函數,所以,可以把整個閉包替換成了>函數,舉個例子:
let block: (Int, Int) -> (Int) = { $0 + $1 }
func testBlock(block: (Int, Int) -> (Int)) -> Int {
return block(1,3)
}
testBlock{ $0 + $1 } //3
testBlock(block: block) //3
4.尾隨閉包(Trailing Closures)
If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is written after the function call’s parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call.
如果函數的最後一個參數是閉包,可以使用尾隨閉包代替,舉個例子:
func someFunctionThatTakesAClosure(closure: () -> Void) {
// function body goes here
}
// Here's how you call this function without using a trailing closure:
//沒有使用尾隨閉包的函數調用情況
someFunctionThatTakesAClosure(closure: {
// closure's body goes here
})
// Here's how you call this function with a trailing closure instead:
//使用了尾隨閉包函數的調用情況
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
以數組的排序函數作為例子來看一下:
let numbers = [1, 3, 2, 4, 7, 8, 5]
let sortedNums = numbers.sorted(by: { $0 > $1 }) //沒有使用尾隨閉包,整個閉包寫在sorted函數參數圓括弧內,閉包內容多的話會顯的很亂
let sortedNums = numbers.sorted() { $0 > $1 } //使用尾隨閉包,這樣會使代碼看起來很整潔
swift里還有一個規則,如果函數只有閉包一個參數,作為尾隨閉包,可以把()去掉,使代碼更為簡潔,代碼如下:
let numbers = [1, 3, 2, 4, 7, 8, 5]
let sortedNums = numbers.sorted(){ $0 > $1 } //沒有去掉"()"
let sortedNums = numbers.sorted { $0 > $1 } //去掉"()"
5.閉包捕獲值(Capturing Values)
A closure can capture constants and variables from the surrounding context in which it is defined.
閉包可以捕獲包裹它的上下文所定義的常量和變數。
(1)全局函數
var number = 0
var add = {
number += 1
print(number)
}
add() //1
add() //2
add() //3
print(number) //3
從上面的代碼可以看出來,閉包捕獲的是值的引用,當閉包內修改閉包外的值,閉包外的值也會跟著改變。
(2)函數嵌套函數
func makeIncrementer(from start: Int, amount: Int) -> ()->Int {
var number = start
return {
number += amount
return number
}
}
let incrementer = makeIncrementer(from: 0, amount: 1)
incrementer() //1
incrementer() //2
incrementer() //3
函數makeIncrementer返回的是一個沒有參數返回整數的函數(閉包),所以,常量incrementer其實就是一個函數。每次調用incrementer()都會執行閉包裡面的操作,而閉包的上下文就是makeIncrementer函數。從這也可以看出來,函數既能當返回值,也可以做參數,在swift妥妥的一等公民,比在Object-C的功能強大多了。
(3)swift中closure(閉包)和Object-C中block的區別
//block
NSInteger number = 1;
NSMutableString *str = [NSMutableString stringWithString: @"hello"];
void(^block)() = ^{
NSLog(@"%@--%ld", str, number);
};
[str appendString: @" world!"];
number = 5;
block(); //hello world!--1
//closure
var str = "hello"
var number = 1
let block = {
print(str + "--" + " \(number)")
}
str.append(" world!")
number = 5
block() //hello world!--5
一句話來說,block內部會對值類型做一份複製,並不指向之前的值的記憶體地址,而對於對象類型則會指向對象當前的記憶體地址,所以修改number時,block里的number數值不變,而修改字元串時,block里的字元串則改變了;closure則預設給外部訪問的變數加上了__block修飾詞的block。至於閉包里的迴圈引用,可以看一下OC與Swift閉包對比總結這篇文章。
6.逃逸閉包(Escaping Closures)
A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.
逃逸閉包,指的是當一個函數有閉包作為參數,但是閉包的執行比函數的執行要遲。通俗來說,這個閉包的作用域本來是在當前函數裡面的,然後它要逃出這個作用域,不想和函數同歸於盡。那麼閉包怎麼逃逸呢?最簡單的方法是把閉包賦值給外面的變數,舉個例子:
var completionHandlers: [() -> Void] = []
//必須加上@escaping,不然編譯會報錯
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
completionHandlers.append(completionHandler)
}
someFunctionWithEscapingClosure {
print("hello")
} //函數執行完,不會列印"hello"
completionHandlers.first?() //列印"hello"
如果逃逸閉包訪問的是類裡面的成員,必須帶上self來訪問;如果訪問的是全局的變數,則和非逃逸閉包一樣。我的理解是,既然閉包逃逸了,則出了函數的作用域,則如果需要訪問類裡面的成員也找不到地址,因為函數已經被銷毀,所以,需要帶上類的地址self指針。
var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
completionHandlers.append(completionHandler)
}
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)
// Prints "200"
completionHandlers.first?()
print(instance.x)
// Prints "100"
7.自動閉包(Autoclosures)
An autoclosure is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it. This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.
自動閉包,我理解是,沒有參數,函數體只有返回值,沒有多餘的其他變數,舉個例子:
let printStr = { "hello" }
print(printStr()) //hello
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let customerProvider = { customersInLine.remove(at: 0) }
print("Now serving \(customerProvider())!") // Prints "Now serving Chris!"
註意:要保證自動閉包裡面代碼能正確執行,比如,在執行customerProvider()之前把數組清空,那麼執行customerProvider()會報錯,代碼如下:
customersInLine.removeAll()
customerProvider() //fatal error: Index out of range
自動閉包作為函數參數,不寫"{}",直接寫返回值:
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
//一般閉包
func serve(customer customerProvider: () -> String) {
print("Now serving \(customerProvider())!")
}
serve(customer: {customersInLine.remove(at: 0)}) //Now serving Chris!
//自動閉包
func serve(customer customerProvider: @autoclosure () -> String) {
print("Now serving \(customerProvider())!")
}
serve(customer: customersInLine.remove(at: 0)) //Now serving Chris!
逃逸的自動閉包:
var customersInLine = ["Barry", "Daniella"]
// 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!"
8.總結
swift的閉包比Object-C的block功能強大很多,更簡潔,更高效。而且,很多集合類型都集成了閉包,比如:map,flatMap等等。這些閉包的功能都很強大,也為swift添加了不少便利性。
原文鏈接:http://www.jianshu.com/p/a618d5fd9881