Swift 中經常遇到一些不熟悉的關鍵字, 例如@autoclosure
, @noescape
...等等, 為什么要加這樣的關鍵字, 我自己寫方法的時候什么時候要加, 什么時候不加, 都是應該考慮的問題, 所以打算寫一系列文章來介紹一下這些關鍵字.
@noescape
@noescape
用來標記一個閉包, 用法如下
func hostFunc(@noescape closure: () -> ()) -> Void
@noescape
字面意思是無法逃脫. 在上例中, closure
被@noescape
修飾, 則聲明 closure
的生命周期不能超過 hostFunc
, 并且, closure
不能被hostFunc
中的其他閉包捕獲(也就是強持有).
用例
func hostFunc(@noescape closure: () -> ()) -> Void {
//以下編譯出錯, closure 被修飾后, 不能被其他異步線程捕獲
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
closure()
}
}