Sobes.tech
Junior — Middle

What is the difference in using the keywords 'unowned' and 'strong' when declaring references in Swift?

sobes.tech AI

Answer from AI

In Swift, the keywords strong and unowned are used for managing references and preventing retain cycles.

  • strong — this is the default strong reference, which increases the reference count of an object. As long as there is at least one strong reference, the object will not be deallocated.

  • unowned — this is a weak, but non-optional reference. It does not increase the reference count, but assumes that the object it references always exists during its use. If the object has been deallocated, accessing an unowned reference will cause a runtime error.

Example:

class Person {
    var apartment: Apartment?
}

class Apartment {
    unowned let tenant: Person
    init(tenant: Person) {
        self.tenant = tenant
    }
}

let john = Person()
let apt = Apartment(tenant: john)
john.apartment = apt

Here, tenant is declared as unowned because the apartment should not hold a strong reference to the person to avoid a cycle, but it is assumed that the person exists longer than the apartment.

What is the difference in using the keywords… - sobes.tech