Sobes.tech
Junior

What is the difference between `weak` and `strong` references in Swift?

sobes.tech AI

Answer from AI

In Swift, strong and weak references relate to memory management and help avoid retain cycles.

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

  • Weak reference — this is a reference that does not increase the reference count. It is used for references that should not keep the object in memory to prevent retain cycles.

If the object referenced by a weak reference is deallocated, the weak reference automatically becomes nil.

Example:

class Person {
    var name: String
    var apartment: Apartment?
    init(name: String) { self.name = name }
}

class Apartment {
    let unit: String
    weak var tenant: Person?  // weak reference
    init(unit: String) { self.unit = unit }
}

var john: Person? = Person(name: "John")
var unit4A: Apartment? = Apartment(unit: "4A")

john!.apartment = unit4A
unit4A!.tenant = john

john = nil  // Person object will be deallocated, weak reference tenant becomes nil

Thus, weak references help prevent memory leaks by allowing objects to reference each other without creating retain cycles.

What is the difference between `weak` and `strong`… - sobes.tech