Bird
Raised Fist0
Swiftprogramming~20 mins

Why ARC matters for Swift developers - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift ARC Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code involving ARC?
Consider the following Swift code that uses classes and ARC. What will be printed when the code runs?
Swift
class Person {
    let name: String
    init(name: String) {
        self.name = name
        print("\(name) is initialized")
    }
    deinit {
        print("\(name) is being deinitialized")
    }
}

var person1: Person? = Person(name: "Alice")
var person2 = person1
person1 = nil
print("person1 is set to nil")
person2 = nil
print("person2 is set to nil")
A
Alice is initialized
person1 is set to nil
Alice is being deinitialized
person2 is set to nil
B
Alice is initialized
Alice is being deinitialized
person1 is set to nil
person2 is set to nil
C
person1 is set to nil
person2 is set to nil
Alice is initialized
Alice is being deinitialized
D
Alice is initialized
person1 is set to nil
person2 is set to nil
Alice is being deinitialized
Attempts:
2 left
💡 Hint
Think about when ARC releases the object based on strong references.
🧠 Conceptual
intermediate
1:30remaining
Why does ARC prevent memory leaks in Swift?
Which statement best explains why ARC helps prevent memory leaks in Swift?
AARC automatically frees memory when there are no more strong references to an object.
BARC requires manual calls to free memory after using an object.
CARC duplicates objects to avoid memory leaks.
DARC disables reference counting for value types.
Attempts:
2 left
💡 Hint
Think about how ARC tracks object usage.
🔧 Debug
advanced
2:30remaining
Identify the cause of the memory leak in this Swift code
This Swift code creates a memory leak. What causes the leak?
Swift
class Person {
    let name: String
    var apartment: Apartment?
    init(name: String) { self.name = name }
    deinit { print("Person \(name) is deinitialized") }
}

class Apartment {
    let unit: String
    var tenant: Person?
    init(unit: String) { self.unit = unit }
    deinit { print("Apartment \(unit) is deinitialized") }
}

var person: Person? = Person(name: "Bob")
var apartment: Apartment? = Apartment(unit: "4A")
person!.apartment = apartment
apartment!.tenant = person

person = nil
apartment = nil
AStrong reference cycle between Person and Apartment causing neither to be deinitialized.
BThe classes use value types instead of reference types.
CThe variables person and apartment are not set to nil properly.
DThe deinit methods are missing calls to free memory.
Attempts:
2 left
💡 Hint
Look at how the two classes reference each other.
📝 Syntax
advanced
1:30remaining
Which option correctly declares a weak reference in Swift?
You want to avoid a strong reference cycle by declaring a weak reference. Which of the following is the correct syntax?
Avar delegate weak: SomeDelegate?
Bvar weak delegate: SomeDelegate?
Cweak var delegate: SomeDelegate?
Dvar delegate: weak SomeDelegate?
Attempts:
2 left
💡 Hint
The weak keyword comes before var or let.
🚀 Application
expert
3:00remaining
How many times is the deinit method called in this Swift ARC example?
Given the following Swift code, how many times will the deinit method be called when the program finishes?
Swift
class Node {
    let value: Int
    var next: Node?
    init(value: Int) { self.value = value }
    deinit { print("Node \(value) is deinitialized") }
}

var first: Node? = Node(value: 1)
var second: Node? = Node(value: 2)
var third: Node? = Node(value: 3)

first!.next = second
second!.next = third
third!.next = first

first = nil
second = nil
third = nil
A2 times
B0 times
C3 times
D1 time
Attempts:
2 left
💡 Hint
Consider the strong reference cycle created by the next pointers.

Practice

(1/5)
1. What is the main purpose of Automatic Reference Counting (ARC) in Swift?
easy
A. To automatically manage memory by tracking object references
B. To optimize the speed of Swift code execution
C. To handle user interface layout automatically
D. To compile Swift code into machine language

Solution

  1. Step 1: Understand ARC's role in memory management

    ARC tracks how many references point to an object to manage its memory automatically.
  2. Step 2: Differentiate ARC from other tasks

    ARC does not optimize speed, handle UI layout, or compile code; it focuses on memory.
  3. Final Answer:

    To automatically manage memory by tracking object references -> Option A
  4. Quick Check:

    ARC = memory management [OK]
Hint: ARC counts references to manage memory automatically [OK]
Common Mistakes:
  • Confusing ARC with code compilation
  • Thinking ARC manages UI layout
  • Assuming ARC improves execution speed
2. Which of the following is the correct way to declare a weak reference in Swift?
easy
A. var delegate: weak MyDelegate?
B. weak var delegate: MyDelegate?
C. var weak delegate: MyDelegate?
D. var delegate: MyDelegate weak?

Solution

  1. Step 1: Recall Swift syntax for weak references

    In Swift, the keyword weak comes before the variable declaration type.
  2. Step 2: Check each option's syntax

    weak var delegate: MyDelegate? correctly places weak before var and the type, matching Swift syntax.
  3. Final Answer:

    weak var delegate: MyDelegate? -> Option B
  4. Quick Check:

    Weak reference syntax = "weak var" [OK]
Hint: Use 'weak var' before the variable name for weak references [OK]
Common Mistakes:
  • Placing 'weak' after the variable name
  • Using 'var weak' instead of 'weak var'
  • Omitting the optional '?' for weak references
3. Consider the following Swift code:
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?
medium
A. Runtime error
B. "No name"
C. nil
D. "Alice"

Solution

  1. Step 1: Understand reference counting in the code

    Both person1 and person2 point to the same Person object initially, so reference count is 2.
  2. Step 2: Analyze effect of setting person1 to nil

    Setting person1 to nil reduces reference count to 1, but person2 still holds the object.
  3. Step 3: Determine print output

    Since person2 still references the object, person2?.name is "Alice".
  4. Final Answer:

    "Alice" -> Option D
  5. Quick Check:

    Reference count > 0 means object exists [OK]
Hint: Object stays alive if any strong reference exists [OK]
Common Mistakes:
  • Assuming object is deallocated when one reference is nil
  • Confusing optional chaining output
  • Expecting runtime error due to nil assignment
4. Given this Swift code snippet, what is the main problem?
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 = first
medium
A. Syntax error in class definition
B. Runtime crash due to nil unwrapping
C. Strong reference cycle causing memory leak
D. No problem, code runs fine

Solution

  1. Step 1: Identify references between nodes

    first points to second, and second points back to first, creating a cycle.
  2. 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.
  3. Final Answer:

    Strong reference cycle causing memory leak -> Option C
  4. Quick Check:

    Strong cycles = memory leaks [OK]
Hint: Check for mutual strong references causing leaks [OK]
Common Mistakes:
  • Thinking this causes syntax errors
  • Assuming ARC handles cycles automatically
  • Ignoring possibility of memory leaks
5. You have two classes, 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?
hard
A. Declare Teacher's students as strong and Student's teacher as weak
B. Declare both references as strong
C. Declare Teacher's students as weak and Student's teacher as strong
D. Declare both references as weak

Solution

  1. Step 1: Identify ownership direction

    The Teacher owns the list of Student objects, so this should be a strong reference.
  2. Step 2: Avoid strong cycle by making reverse reference weak

    The Student references back to Teacher should be weak to prevent a strong reference cycle.
  3. Final Answer:

    Declare Teacher's students as strong and Student's teacher as weak -> Option A
  4. Quick Check:

    Strong ownership one way, weak back reference [OK]
Hint: Make back references weak to break strong cycles [OK]
Common Mistakes:
  • Making both references strong causing leaks
  • Making both references weak causing premature deallocation
  • Confusing which side should be weak
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard