Sometimes two objects keep each other alive by holding strong references. This causes a memory problem called a cycle. Weak references help stop this by not keeping the other object alive.
Weak references to break cycles in Swift
class SomeClass { weak var otherObject: OtherClass? }
Use the weak keyword before the variable to make it a weak reference.
Weak references must be optional because the referenced object can disappear (become nil).
Person class has a weak reference to Apartment to avoid a cycle.class Person { var name: String weak var apartment: Apartment? init(name: String) { self.name = name } }
Apartment class has a strong reference to Person.class Apartment { let unit: String var tenant: Person? init(unit: String) { self.unit = unit } }
john and unit4A refer to each other, but john.apartment is weak, so no cycle occurs.let john = Person(name: "John") let unit4A = Apartment(unit: "4A") john.apartment = unit4A unit4A.tenant = john
This program creates a Person and an Apartment that refer to each other. The Person holds a weak reference to the Apartment. When both variables are set to nil, both objects are properly cleaned up because there is no strong cycle.
class Person { let name: String weak var apartment: Apartment? init(name: String) { self.name = name print("Person \(name) is created") } deinit { print("Person \(name) is being deinitialized") } } class Apartment { let unit: String var tenant: Person? init(unit: String) { self.unit = unit print("Apartment \(unit) is created") } deinit { print("Apartment \(unit) is being deinitialized") } } var john: Person? = Person(name: "John") var unit4A: Apartment? = Apartment(unit: "4A") john!.apartment = unit4A unit4A!.tenant = john john = nil unit4A = nil
Weak references do not increase the reference count of the object.
If the referenced object is deallocated, the weak reference automatically becomes nil.
Use unowned references only when you are sure the referenced object will never be nil during the lifetime of the reference.
Weak references help avoid memory cycles by not keeping objects alive.
They must be optional because the object they point to can disappear.
Use weak references in relationships where one object should not own the other strongly.