Sobes.tech
Junior — Senior

What changes when replacing unowned with weak in object relationships

livecode

Task condition

Question: How will the program's behavior change if, instead of using a reference with the unowned modifier, weak is used? Consider an example in Swift where one object holds a strong reference to another, and the second object holds a back reference to the first.

class Individual {
    var fullName: String
    var device: Device?
    init(fullName: String) { self.fullName = fullName }
}

class Device {
    var type: String
    unowned var owner: Individual
    init(type: String, owner: Individual) {
        self.type = type
        self.owner = owner
    }
}

var individual: Individual? = Individual(fullName: "Alice")
individual?.device = Device(type: "iPhone", owner: individual!)
individual = nil

Describe what happens to the objects after setting individual = nil when using unowned, and then explain how the situation changes if unowned var owner: Individual is replaced with weak var owner: Individual?.