0
0
Swiftprogramming~5 mins

ARC overview for memory management in Swift

Choose your learning style9 modes available
Introduction

ARC helps your app manage memory automatically. It keeps track of how many parts of your code use a piece of data and frees it when no one needs it anymore.

When you create objects that need to be stored in memory.
When you want to avoid memory leaks in your app.
When you want your app to run smoothly without using too much memory.
When you work with classes and want to understand how Swift manages their memory.
When you want to debug issues related to objects not being released.
Syntax
Swift
class MyClass {
    // properties and methods
}

var object: MyClass? = MyClass()
// ARC automatically increases reference count
object = nil
// ARC decreases reference count and frees memory if count is zero

ARC stands for Automatic Reference Counting.

It works only with class instances, not with structs or enums.

Examples
This example shows how ARC creates and then removes a Person object when no references remain.
Swift
class Person {
    let name: String
    init(name: String) {
        self.name = name
        print("Person \(name) is created")
    }
    deinit {
        print("Person \(name) is being removed")
    }
}

var person1: Person? = Person(name: "Anna")
person1 = nil
Here, two variables share the same object. ARC frees memory only when both are nil.
Swift
class Car {
    let model: String
    init(model: String) {
        self.model = model
    }
}

var car1: Car? = Car(model: "Tesla")
var car2 = car1
car1 = nil
// car2 still holds the reference, so Car is not removed
car2 = nil
// now Car is removed
Sample Program

This program shows how ARC tracks references to a Dog object. The Dog is only removed when both dog1 and dog2 are nil.

Swift
class Dog {
    let name: String
    init(name: String) {
        self.name = name
        print("Dog \(name) is born")
    }
    deinit {
        print("Dog \(name) has died")
    }
}

var dog1: Dog? = Dog(name: "Buddy")
var dog2 = dog1

print("Setting dog1 to nil")
dog1 = nil

print("Setting dog2 to nil")
dog2 = nil
OutputSuccess
Important Notes

ARC automatically manages memory without extra code.

Strong references keep objects alive; setting them to nil reduces the count.

Be careful with strong reference cycles, which can cause memory leaks.

Summary

ARC counts how many references point to an object.

When no references remain, ARC frees the object's memory.

This helps keep your app efficient and prevents memory problems.