Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Swift does not dispose circular references (strong reference cycles) automatically

sorry if it's a silly question. I just started learning swift. I mainly use php for my daily job. Apple Store's Swift textbook uses the following example (i modified it into a shorter version) to demonstrate the usage of weak reference:

class Person {
    var apartment: Apartment?;
}

class Apartment {
    weak var tenant: Person?;
}

var john: Person?;           john = Person();
var number73: Apartment?;    number73 = Apartment();
john!.apartment = number73;  number73!.tenant = john;      //circular reference here

john = nil;   number73 = nil;         //deference from static variable names

In the above Apartment class definition, if the weak key word is removed from var tenant, it creates a strong reference cycle in the following code so that the two instances do not get disposed by GC. However, it appears to me the GC really does not need the indication of the weak reference. It is obvious that the two instances can not be linked from any variables in the current scope or from any static variables, so they are safe to be disposed.

Why dose Swift force the syntax? The only advantage I can figure out is the weak key word highlights the logic so the code is easier to read.

like image 963
Peter Li Avatar asked Oct 31 '14 15:10

Peter Li


1 Answers

Swift does not use mark-and-sweep garbage collection. It uses reference counting. In reference counting it is counted how many references there are to each object: each time a new reference to an object is created the reference count is incremented, and each time a reference to the object is removed the reference count is decremented. As soon as an object has zero references, it is disposed. One of the major weaknesses of reference counting is that cyclic structured are not disposed of.

In your example, john has a reference to number73 and number73 has a reference to john. So, if the weak keyword is removed, each object has at least one reference to it, and so none of the objects will be disposed.

Weak references help to break cycles. Basically, weak references are not counted, and thus objects which have only weak references to them will be removed. In the example, since the Apartment instance only has a weak reference to the Person instance, the latter has a reference count of 0 and will be disposed. After that, also the Apartment instance has a reference count of 0 and will also be disposed.

like image 159
Hoopje Avatar answered Nov 08 '22 23:11

Hoopje