Book Image

Learning Swift

By : Andrew J Wagner
Book Image

Learning Swift

By: Andrew J Wagner

Overview of this book

Table of Contents (18 chapters)
Learning Swift
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Lost objects


It is a great idea to always keep strong reference cycles in mind, but if we are too aggressive with the use of weak and unowned references, we can run into the opposite type of problem, where an object is deleted before we intend to delete it.

Between objects

With an object, this will happen if all the references to the object are weak or unowned. This won't be a fatal mistake if we use weak references, but if this happens with an unowned reference, it will crash your program.

For example, let's look at our earlier example with an extra weak reference:

class SteeringWheel3 {
    weak var car: Car3?
}

class Car3 {
    weak var steeringWheel: SteeringWheel3?
    
    init(steeringWheel: SteeringWheel3) {
        self.steeringWheel = steeringWheel
        self.steeringWheel!.car = self
    }
}

let wheel3 = SteeringWheel3()
let car3 = Car3(steeringWheel: wheel3)

This code is the same as the previous, except that both the car property of SteeringWheel3 and the steeringWheel property...