Swift: The rules of being unowned (Xcode 6 Beta 7)


Continuing on from Swift: The rules of being weak, this post considers the rules of employing weak's ally in the fight against strong reference cycles, unowned.

Rules of the unowned keyword

Here are the rules of the unowned keyword
  1. it can be used inside classes, structs, enums and protocols
  2. it can be used with constants, variables and properties
  3. the variables and properties it is used with must not be optionals
  4. it cannot be used to declare (or set) variables that are non-class types, for example unowned var a:String would raise a compiler error (as will all of Swift's own types, since they are all structs and enums)
And while it might be an obvious point, an unowned reference must be paired with a regular (strong) reference to be of practical use. This, for instance, would be a pointless assignment on its own:
unowned var a:Person = Person(name: "John Appleseed") // nil
 

Don't be a crash test dummy

Testing Apple's code examples of a strong reference cycle won't crash your app if you simply remove the unowned keyword. This is a warning sign that awareness of strong reference cycles needs to be learnt, rather than discovered in research after a crash.

The major indicator that you need to employ unowned or weak keywords is that you have two class instances owning (or referencing) one another in their properties or in variables. In which case you need to make one of those references either weak or unowned.

Tips for testing unowned

A couple of tips for testing the deintiliazation:
  1. you must use the Simulator, not a Playground, in order to see the deinitialization taking place
  2. even with strong references, ARC deinitializes as soon as possible, which means that if you place the variable declarations in the same method as the assignments then once that method has ended the instances will be released and deinitialized anyway without even setting the strong references to nil
Note: discussion of the use of unowned in closures will follow in a later post.


Endorse on Coderwall

Comments