Sobes.tech
Junior — Middle

Kas Swift sisaldab automaatset mälu kogumist, sarnaselt GC teiste keeltega?

sobes.tech AI

Vastus AI-lt

In Swift, automatic garbage collection (GC) is not used in the traditional sense, as in Java or C#. Instead, Swift employs an automatic reference counting system (ARC — Automatic Reference Counting). ARC automatically tracks the number of references to an object and frees the memory when there are no more references.

Example:

class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var person1: Person? = Person(name: "Ivan")
var person2 = person1 // increases reference count
person1 = nil // the object still lives, as person2 references it
person2 = nil // now the object is released

Thus, ARC works automatically, but without pauses and overhead typical of traditional garbage collectors.