O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Breaking Strong Reference Cycles with weak

The solution to a strong reference cycle is to break the cycle. You could manually break the cycles by looping over each asset and setting its owner to nil immediately after you set bob to nil, but that is tedious and error prone. Instead, Swift provides a keyword to get the same effect automatically. Modify Asset to make the owner property a weak reference instead of a strong reference.

Listing 24.7 Making the owner property a weak reference (Asset.swift)

import Foundation

class Asset: CustomStringConvertible {
    let name: String
    let value: Double
    weak var owner: Person?
    ...
}

A weak reference is a reference that does not increase the reference count of the instance it refers to. In ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required