ARC helps Swift manage memory automatically so your app runs smoothly without using too much memory or crashing.
Why ARC matters for Swift developers
// ARC works behind the scenes in Swift; no special syntax needed. // But you can use 'weak' and 'unowned' to avoid strong reference cycles. class Person { var name: String weak var apartment: Apartment? init(name: String) { self.name = name } } class Apartment { let unit: String unowned let tenant: Person init(unit: String, tenant: Person) { self.unit = unit self.tenant = tenant } }
ARC automatically counts how many references point to an object and frees it when none remain.
Use weak and unowned to prevent memory leaks caused by objects referencing each other strongly.
Person and Apartment hold strong references to each other, so ARC cannot free them.class Person { var name: String var apartment: Apartment? init(name: String) { self.name = name } } class Apartment { let unit: String var tenant: Person? init(unit: String) { self.unit = unit } } var john: Person? = Person(name: "John") var unit4A: Apartment? = Apartment(unit: "4A") john!.apartment = unit4A unit4A!.tenant = john john = nil unit4A = nil
weak for apartment breaks the strong reference cycle, so ARC can free both objects when no longer needed.class Person { var name: String weak var apartment: Apartment? init(name: String) { self.name = name } } class Apartment { let unit: String var tenant: Person? init(unit: String) { self.unit = unit } } var john: Person? = Person(name: "John") var unit4A: Apartment? = Apartment(unit: "4A") john!.apartment = unit4A unit4A!.tenant = john john = nil unit4A = nil
This program shows how ARC frees memory when objects are no longer needed. The deinit messages confirm objects are cleaned up.
class Person { let name: String weak var apartment: Apartment? init(name: String) { self.name = name print("Person \(name) is initialized") } deinit { print("Person \(name) is being deinitialized") } } class Apartment { let unit: String unowned let tenant: Person init(unit: String, tenant: Person) { self.unit = unit self.tenant = tenant print("Apartment \(unit) is initialized") } deinit { print("Apartment \(unit) is being deinitialized") } } var john: Person? = Person(name: "John") var unit4A: Apartment? = Apartment(unit: "4A", tenant: john!) john!.apartment = unit4A john = nil unit4A = nil
ARC only works with class instances, not with structs or enums.
Strong reference cycles cause memory leaks and can crash your app if not handled.
Use weak when the reference can become nil, and unowned when it should never be nil during the object's lifetime.
ARC automatically manages memory by counting references to objects.
Strong reference cycles can cause memory leaks; use weak and unowned to avoid them.
Understanding ARC helps you write efficient and crash-free Swift apps.