Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift is the programmer responsible for breaking loops between objects?

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?

like image 224
Ian Ringrose Avatar asked Jun 03 '14 08:06

Ian Ringrose


1 Answers

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.

like image 71
Leandros Avatar answered Nov 13 '22 16:11

Leandros