Where do I define captured references for nested closures in Swift?
Take this code as an example:
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.
*/
}
}
In this example, [weak self]
is used in both trailing closures, however the compiler is perfectly happy if I omit [weak self]
from either one of the trailing closures.
So that leaves me 3 options for defining my capture list:
- define captures on every nested closure leading up to the reference
- define captures on the first closure only.
- define captures on only the most nested closure that actually uses the reference.
My question is:
If I know that my
ExampleDataSource
could benil
at some point, what is the best option to go with?