Cyclic strong references in closures
Resolving cyclic strong references between closures and class instances can be achieved by defining a capture list.
Capture List
Each element in the capture list is made up of a reference to the weak or unowned keyword and instance, such as self. Each pair is enclosed in square brackets, separated by commas:
Lazyvar someclosure: (Int, String) String = {[unowned self] (Index:int, stringtoprocess:string) Stringinch}
We need to determine whether a property in the capture list is a weak or a non-primary reference, with the following criteria:
- When the instances of closures and captures are always referencing each other and are always destroyed at the same time, the captures within the closures are defined as non-primary references.
- When a capture reference is sometimes possible
nil
, it is defined as a weak reference. A weak reference is always an optional type, and when the referenced instance is destroyed, the value of the weak reference is automatically set to nil
. This allows us to check if they exist within the closures.
For example, the following code:
classHtmlElement { LetNameString LetTextString? LazyvarAshtml: ()String= {[unowned self]inch if LetText = self.text {return "<\ (self.name) >\ (text) </\ (self.name) >"}Else{return "<\ (self.name)/>"}} init (name:String, Text:String? = nil) {self.name = name Self.text = text} deinit {println ("\ (name) is being deinitialized") }}varParagraph:htmlelement? = HtmlElement (Name:"P", Text:"Hello, World") println (paragraph!. Ashtml ())
is actually defined asweak
is also possible (bar), just need to unpack each time, and actuallyself
Impossible fornil
, so there is no point in defining such a definition. Use a no-master reference to Better Expressself
The state.
Summary
The basic part of the official document has finally been read over, time is limited, many details did not start learning, only in the back of the study to fill up.
Next, plan to look at some open source projects and learn more about Swift's use by reading someone else's source code.
Cheer Up ~
(Ah recently too water I am embarrassed, the basic is to copy the official website example Ah!) No no no, tomorrow will be good work! )
References
- Automatic Reference Counting
[Swift] DAY15: Cyclic strong references in closures