我在哪裏定義捕獲的Swift嵌套閉包引用?在swift中正確放置捕獲列表嵌套閉包
以將該代碼作爲一個例子:
import Foundation
class ExampleDataSource {
var content: Any?
func loadContent() {
ContentLoader.loadContentFromSource() { [weak self] loadedContent in
// completion handler called on background thread
dispatch_async(dispatch_get_main_queue()) { [weak self] in
self?.content = loadedContent
}
}
}
}
class ContentLoader {
class func loadContentFromSource(completion: (loadedContent: Any?) -> Void) {
/*
Load content from web asynchronously,
and call completion handler on background thread.
*/
}
}
在這個例子中,在[weak self]
後兩者封被使用,但是如果我省略[weak self]
編譯器是完全快樂從尾部封閉件中的任一個。
所以這讓我定義我的捕獲列表3個選項:
- 每封嵌套領導到基準
- 只在第一封定義捕獲定義捕獲。
- 僅在實際使用引用的最嵌套閉包上定義捕獲。
我的問題是:
如果我知道我的
ExampleDataSource
可能在某些時候是nil
,究竟是去與最好的選擇?