Welcome back! In this lesson, we'll dive deep into Swift's strong references. Let's begin! 🚀
Strong references in Swift are connections between two variables that keep an object alive in memory. When a strong reference exists, the object is not deallocated (or destroyed) until the last strong reference to it is removed.
Let's visualize it with an example:
class Car {
var model: String
init(model: String) {
self.model = model
print("Car created: \(model)")
}
}
var car1 = Car(model: "Tesla")
var car2 = car1 // Strong reference created between car1 and car2
// Car created: Tesla
car1 = Car(model: "BMW") // car1's reference is now pointing to a new object, but car2 still points to the original "Tesla" object.
// Car created: BMW
// Car created: Tesla (This is because car2 still points to the original "Tesla" object)Be aware of retaining cycles that can lead to memory leaks. A retaining cycle occurs when two objects maintain strong references to each other, keeping both of them alive in memory even when they are no longer needed.
Let's see an example of a retaining cycle:
class Person {
var name: String
var car: Car?
init(name: String) {
self.name = name
print("\(name) created")
}
}
class Car {
var owner: Person?
init(owner: Person) {
self.owner = owner
owner.car = self
print("Car created for \(owner.name)")
}
}
var john = Person(name: "John")
var carJohn = Car(owner: john)
// John created
// Car created for John
// If john and carJohn are no longer needed, they will still remain in memory because of the retaining cycle.
// To break the cycle, set the owner property to nil when the car is no longer needed:
carJohn.owner = nilWhat is the purpose of strong references in Swift?
What happens when all strong references to an object are removed in Swift?
Stay tuned for the next lesson on weak and unowned references! 🎓