Bird
Raised Fist0
Swiftprogramming~20 mins

Actor isolation concept in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Actor Master
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 actor code?

Consider this Swift code using an actor. What will be printed when printCounter() is called?

Swift
actor Counter {
    var value = 0
    func increment() {
        value += 1
    }
    func printCounter() {
        print("Counter value: \(value)")
    }
}

let counter = Counter()
Task {
    await counter.increment()
    await counter.printCounter()
}
ARuntime error due to actor isolation violation
BCounter value: 1
CCompilation error due to missing await
DCounter value: 0
Attempts:
2 left
💡 Hint

Remember that actor methods must be called with await outside the actor.

🧠 Conceptual
intermediate
1:30remaining
Which statement best describes actor isolation in Swift?

Choose the statement that correctly explains actor isolation.

AActors isolate their mutable state to ensure only one task accesses it at a time.
BActors allow shared mutable state without any synchronization.
CActors require all methods to be synchronous to avoid data races.
DActors automatically copy their state when accessed from multiple tasks.
Attempts:
2 left
💡 Hint

Think about how actors protect their data from concurrent access.

🔧 Debug
advanced
2:00remaining
What error does this Swift code produce?

Examine this code snippet. What error will the compiler report?

Swift
actor BankAccount {
    var balance = 1000
    func deposit(amount: Int) {
        balance += amount
    }
}

let account = BankAccount()
account.deposit(amount: 500)
AError: Call to actor-isolated method 'deposit' in a synchronous context requires 'await'
BError: Cannot mutate 'balance' because it is a constant
CNo error, code runs successfully
DError: Missing 'async' keyword in function declaration
Attempts:
2 left
💡 Hint

Think about how actor methods must be called from outside the actor.

📝 Syntax
advanced
1:30remaining
Which option correctly declares an actor with an isolated mutable property?

Choose the correct Swift code that declares an actor with a mutable property count initialized to 0.

A
actor Counter {
    let count = 0
}
B
actor Counter {
    var count: Int
    init() { count = 0 }
}
C
actor Counter {
    static var count = 0
}
D
actor Counter {
    var count: Int = 0
}
Attempts:
2 left
💡 Hint

Remember that mutable properties inside actors are declared with var.

🚀 Application
expert
2:30remaining
How many times will the actor's method be executed concurrently?

Given this Swift code, how many concurrent executions of increment() can happen inside the actor?

Swift
actor Counter {
    var value = 0
    func increment() {
        value += 1
    }
}

let counter = Counter()
Task {
    await withTaskGroup(of: Void.self) { group in
        for _ in 1...5 {
            group.addTask {
                await counter.increment()
            }
        }
    }
}
ANo executions happen because increment is not async
B5 concurrent executions happen inside the actor
COnly 1 execution happens at a time due to actor isolation
DExecutions run concurrently but cause a data race
Attempts:
2 left
💡 Hint

Think about how actor isolation serializes access to its mutable state.

Practice

(1/5)
1. What is the main purpose of actor isolation in Swift concurrency?
easy
A. To disable concurrency features in Swift
B. To ensure only one task accesses actor data at a time
C. To make actor methods run faster without waiting
D. To allow multiple tasks to modify actor data simultaneously

Solution

  1. Step 1: Understand actor isolation concept

    Actor isolation means only one task can access the actor's data at a time to avoid conflicts.
  2. Step 2: Compare options with this concept

    Only To ensure only one task accesses actor data at a time correctly describes this purpose; others contradict the idea of isolation.
  3. Final Answer:

    To ensure only one task accesses actor data at a time -> Option B
  4. Quick Check:

    Actor isolation = single task access [OK]
Hint: Actor isolation means single task access only [OK]
Common Mistakes:
  • Thinking actors allow simultaneous data changes
  • Confusing isolation with performance boost
  • Believing actor isolation disables concurrency
2. Which of the following is the correct way to call an actor's method from outside the actor in Swift?
easy
A. await actorInstance.method()
B. actorInstance.method()
C. async actorInstance.method()
D. actorInstance.method.await()

Solution

  1. Step 1: Recall syntax for calling actor methods

    Calling an actor's method from outside requires using await to handle asynchronous access.
  2. Step 2: Match options with correct syntax

    Only await actorInstance.method() uses await correctly before the method call.
  3. Final Answer:

    await actorInstance.method() -> Option A
  4. Quick Check:

    Use await before actor method call [OK]
Hint: Always use await before calling actor methods externally [OK]
Common Mistakes:
  • Omitting await causing compile errors
  • Using async keyword incorrectly
  • Placing await after method call
3. Consider this Swift code snippet:
actor Counter {
    var value = 0
    func increment() {
        value += 1
    }
}

let counter = Counter()
Task {
    await counter.increment()
    print(await counter.value)
}
What will be printed when this code runs?
medium
A. 1
B. 0
C. Compilation error
D. Runtime crash

Solution

  1. Step 1: Understand actor method and property access

    The method increment() increases value by 1. Accessing value outside requires await.
  2. Step 2: Trace code execution

    The task calls await counter.increment() which adds 1, then prints await counter.value, so output is 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Increment then print value = 1 [OK]
Hint: Increment then await value to print updated number [OK]
Common Mistakes:
  • Forgetting await on property access
  • Assuming value remains 0 without increment
  • Expecting compile or runtime errors
4. Identify the error in this Swift actor usage:
actor BankAccount {
    var balance = 1000
    func withdraw(amount: Int) {
        balance -= amount
    }
}

let account = BankAccount()
account.withdraw(amount: 100)
print(account.balance)
medium
A. Cannot print actor properties
B. balance should be a constant
C. withdraw method must be static
D. Missing await when calling actor method

Solution

  1. Step 1: Check actor method call rules

    Calling an actor's method from outside must use await because it is asynchronous.
  2. Step 2: Identify missing await

    The code calls account.withdraw(amount: 100) without await, causing a compile error.
  3. Final Answer:

    Missing await when calling actor method -> Option D
  4. Quick Check:

    Actor method calls need await [OK]
Hint: Always await actor method calls outside actor [OK]
Common Mistakes:
  • Calling actor methods without await
  • Thinking actor properties can't be printed
  • Believing methods must be static
5. You want to safely update a shared counter from multiple tasks using an actor. Which approach correctly ensures safe concurrent increments?
hard
A. Use a global variable and increment without synchronization
B. Use a struct with a mutating method called from multiple tasks
C. Define an actor with a method to increment the counter and call it with await
D. Use a class with a property and increment it directly from tasks

Solution

  1. Step 1: Understand concurrency safety requirements

    Shared data must be accessed safely to avoid race conditions; actors provide this by isolating data.
  2. Step 2: Evaluate each option for safety

    Define an actor with a method to increment the counter and call it with await uses an actor with an increment method called with await, ensuring safe access. Others lack synchronization.
  3. Final Answer:

    Define an actor with a method to increment the counter and call it with await -> Option C
  4. Quick Check:

    Actor method with await ensures safe concurrent updates [OK]
Hint: Use actor methods with await for safe shared data updates [OK]
Common Mistakes:
  • Ignoring synchronization with global variables
  • Using structs or classes without concurrency control
  • Assuming direct property access is safe
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