Sobes.tech
Junior — Middle

Can you give an example of when the `unowned` operator is used in Swift code?

sobes.tech AI

Answer from AI

The unowned operator in Swift is used to declare a weak reference that is not optional and assumes that the object it refers to always exists during access. This is useful for preventing strong reference cycles, for example, when working with closures or mutually referencing objects, where one object is guaranteed to outlive the other.

Example of using unowned in a closure:

class Person {
    let name: String
    var apartment: Apartment?

    init(name: String) {
        self.name = name
    }

    lazy var printApartment = { [unowned self] in
        if let apt = self.apartment {
            print("\(self.name) lives in apartment \(apt.number)")
        } else {
            print("\(self.name) has no apartment")
        }
    }
}

class Apartment {
    let number: Int
    unowned let tenant: Person

    init(number: Int, tenant: Person) {
        self.number = number
        self.tenant = tenant
    }
}

let john = Person(name: "John")
let apt1 = Apartment(number: 101, tenant: john)
john.apartment = apt1

john.printApartment() // Will print: John lives in apartment 101

Here, unowned is used for the reference from Apartment to Person, to avoid a strong reference cycle, assuming that Person lives longer than Apartment.

Can you give an example of when the `unowned`… - sobes.tech