[Please] About "Unowned Optional References"

Automatic Reference Counting — The Swift Programming Language (Swift 5.4) > Unowned Optional References Section.

class Department {
    var name: String
    var courses: [Course]
    init(name: String) {
        self.name = name
        self.courses = []
    }
}

class Course {
    var name: String
    unowned var department: Department
    unowned var nextCourse: Course?
    init(name: String, in department: Department) {
        self.name = name
        self.department = department
        self.nextCourse = nil
    }
}

Department and Course class

and original code

let department = Department(name: "Horticulture")
let intro = Course(name: "Survey of Plants", in: department)
let intermediate = Course(name: "Growing Common Herbs", in: department)
let advanced = Course(name: "Caring for Tropical Plants", in: department)
intro.nextCourse = intermediate
intermediate.nextCourse = advanced
department.courses = [intro, intermediate, advanced]

Why did Apple declare the nextCourse as unowned?
If it is declared weak, it is natural that if the intermediate course becomes nil, the nexCourse of the intro is naturally nil.

I don't understand...

An unowned flavor weak-reference (not the keyword weak) to a property just says that it is not participating in lifetime management of the referenced object. In this case, it implies that the department and nextCourse is guaranteed to live as long as, or outlive the course referring to it. I think I remember reading a document that mentioned they considered the name dangling instead of unowned before Swift became public.

I think, as you correctly understand, if you have objects coming in and out of existence, and are using unowned you need to be really careful. The code will trap if you reference a deallocated object, it won't automatically nil itself out like a weak, weak reference will. Using unowned makes a strong (pun not intended) statement about the relative lifetimes of the objects involved.

1 Like
Terms of Service

Privacy Policy

Cookie Policy