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.
Practice
Solution
Step 1: Understand ARC's role in memory management
ARC tracks how many references point to an object to manage its memory automatically.Step 2: Differentiate ARC from other tasks
ARC does not optimize speed, handle UI layout, or compile code; it focuses on memory.Final Answer:
To automatically manage memory by tracking object references -> Option AQuick Check:
ARC = memory management [OK]
- Confusing ARC with code compilation
- Thinking ARC manages UI layout
- Assuming ARC improves execution speed
Solution
Step 1: Recall Swift syntax for weak references
In Swift, the keywordweakcomes before the variable declaration type.Step 2: Check each option's syntax
weak var delegate: MyDelegate? correctly placesweakbeforevarand the type, matching Swift syntax.Final Answer:
weak var delegate: MyDelegate? -> Option BQuick Check:
Weak reference syntax = "weak var" [OK]
- Placing 'weak' after the variable name
- Using 'var weak' instead of 'weak var'
- Omitting the optional '?' for weak references
class Person {
var name: String
init(name: String) {
self.name = name
}
}
var person1: Person? = Person(name: "Alice")
var person2 = person1
person1 = nil
print(person2?.name ?? "No name")What will be printed?
Solution
Step 1: Understand reference counting in the code
Bothperson1andperson2point to the samePersonobject initially, so reference count is 2.Step 2: Analyze effect of setting
Settingperson1to nilperson1to nil reduces reference count to 1, butperson2still holds the object.Step 3: Determine print output
Sinceperson2still references the object,person2?.nameis "Alice".Final Answer:
"Alice" -> Option DQuick Check:
Reference count > 0 means object exists [OK]
- Assuming object is deallocated when one reference is nil
- Confusing optional chaining output
- Expecting runtime error due to nil assignment
class Node {
var value: Int
var next: Node?
init(value: Int) {
self.value = value
}
}
var first: Node? = Node(value: 1)
var second: Node? = Node(value: 2)
first?.next = second
second?.next = firstSolution
Step 1: Identify references between nodes
firstpoints tosecond, andsecondpoints back tofirst, creating a cycle.Step 2: Understand ARC impact of strong cycles
Both nodes hold strong references to each other, so ARC cannot deallocate them, causing a memory leak.Final Answer:
Strong reference cycle causing memory leak -> Option CQuick Check:
Strong cycles = memory leaks [OK]
- Thinking this causes syntax errors
- Assuming ARC handles cycles automatically
- Ignoring possibility of memory leaks
Teacher and Student, where each Teacher has a list of Student objects, and each Student has a reference to their Teacher. How should you declare these references to avoid memory leaks caused by ARC?Solution
Step 1: Identify ownership direction
TheTeacherowns the list ofStudentobjects, so this should be a strong reference.Step 2: Avoid strong cycle by making reverse reference weak
TheStudentreferences back toTeachershould be weak to prevent a strong reference cycle.Final Answer:
Declare Teacher's students as strong and Student's teacher as weak -> Option AQuick Check:
Strong ownership one way, weak back reference [OK]
- Making both references strong causing leaks
- Making both references weak causing premature deallocation
- Confusing which side should be weak
Ready to prove it?
Pass the test and this pattern moves unknown
