As I understand it, Swift uses automatic reference counting for its garbage collection.
This takes me back many years to when I was a COM programmer.
VB6 (and before) automated the process of decimating the reference count when an object went out of scope, most of the time this was enough to allow a programmer to forget about memory management.
However if there were loops between objects, .e.g
Car->WheelsCollection contains pointers to wheels
Wheel->CurrentCar constrains a pointer to the car the wheel is currently installed on
Then when an instance of the car went out of scope, it would not be garbage collected as the car kept its wheels alive, and the wheels kept the car alive.
What programmer patterns or otherwise are used in Swift to avoid or mitigate this problem?
This is a simple retain cycle, you have to solve it by using a weak reference.
Assuming this as your current classes.
class Car {
var wheel: Wheel?
}
class Wheel {
var currentCar: Car?
}
and your current situation
var myCar: Car? = Car()
var myWheel: Wheel? = Wheel()
myCar!.wheel = myWheel
To solve this, you have to declare one of them as weak
, for example: weak var currentCar: Car?
.
The official Swift documentation, explains it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With