[Swift] Day15: Circular strong reference in the closure
Circular strong references in closures
You can define the capture list to solve the circular strong reference between closures and class instances.
Capture list
Each element in the capture list is composed of the weak or unowned keyword and instance reference (such as self. Each pair is in square brackets separated by commas:
lazy var someClosure: (Int, String) -> String = { [unowned self] (index: Int, stringToProcess: String) -> String in}
We need to determine whether the attributes in the capture list are weak references or no primary references. The following judgment bases are available:
- When the closure and the captured instance are always referenced and destroyed at the same time, the capture in the closure is defined as a non-master reference.
- When capturing a reference, it may be
nil
Is defined as weak reference. Weak references are always optional. When the referenced instance is destroyed, the value of the weak reference is automatically setnil
. This allows us to check whether they exist in the closure.For example, the following code:
class HTMLElement { let name: String let text: String? lazy var asHTML: () -> String = { [unowned self] in if let text = self.text { return "<\(self.name)>\(text)
" } else { return "<\(self.name) />" } } init(name: String, text: String? = nil) { self.name = name self.text = text } deinit { println("\(name) is being deinitialized") }}var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")println(paragraph!.asHTML())
Actually definedweak
It is also possible (right), but each time you need to unpack, but in factself
Impossiblenil
So such a definition is meaningless. Can be better expressed with no primary referenceself
.
SummaryThe basic part of the official document has finally been read, and the time is limited. Many details have not been learned yet, so you can only make up the following.
Next we plan to look at some open-source projects and learn more about using Swift by reading other people's source code.
Come on ~
(Ah, I'm sorry for being too watery recently. I just copied the example on the official website! No. You have to work hard tomorrow !)
References
- Automatic Reference Counting