Bird
Raised Fist0
Swiftprogramming~20 mins

Nonisolated methods in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Actor Isolation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a nonisolated method in an actor
What is the output of this Swift code using a nonisolated method inside an actor?
Swift
actor Counter {
    var value = 0
    nonisolated func description() -> String {
        "Counter value is not accessible here"
    }
    func increment() {
        value += 1
    }
}

let counter = Counter()
print(counter.description())
A0
BCounter value is not accessible here
CCompilation error: actor isolation violation
DRuntime error: data race detected
Attempts:
2 left
💡 Hint
Remember that nonisolated methods run outside the actor's isolation context.
❓ Predict Output
intermediate
2:00remaining
Accessing actor state from nonisolated method
What happens if a nonisolated method tries to access an actor's isolated property directly?
Swift
actor Logger {
    var logs = [String]()
    nonisolated func latestLog() -> String {
        logs.last ?? "No logs"
    }
}

let logger = Logger()
print(logger.latestLog())
ACompilation error: actor-isolated property 'logs' cannot be accessed from nonisolated context
BPrints an empty string
CRuntime error: data race on 'logs'
DPrints the last log or "No logs" if empty
Attempts:
2 left
💡 Hint
Nonisolated methods cannot access actor-isolated properties directly.
🔧 Debug
advanced
2:00remaining
Why does this nonisolated method cause a compile error?
Identify the reason for the compile error in this code snippet.
Swift
actor BankAccount {
    var balance: Int = 1000
    nonisolated func getBalance() -> Int {
        balance
    }
}
AThe method getBalance() must be async to access actor properties.
BThe property 'balance' must be declared nonisolated.
CActors cannot have nonisolated methods.
DNonisolated methods cannot access actor-isolated properties like 'balance'.
Attempts:
2 left
💡 Hint
Think about actor isolation rules and what nonisolated means.
❓ Predict Output
advanced
2:00remaining
Effect of nonisolated on method concurrency
What is the output of this Swift code involving a nonisolated method and an actor?
Swift
actor Printer {
    nonisolated func printMessage() {
        print("Hello from nonisolated method")
    }
    func printIsolatedMessage() {
        print("Hello from isolated method")
    }
}

let printer = Printer()
printer.printMessage()
Task {
    await printer.printIsolatedMessage()
}
AHello from nonisolated method\nHello from isolated method
BHello from isolated method\nHello from nonisolated method
CCompilation error: cannot call isolated method without await
DRuntime error: actor isolation violation
Attempts:
2 left
💡 Hint
Nonisolated methods can be called directly without await.
🧠 Conceptual
expert
2:00remaining
Why use nonisolated methods in actors?
Which of the following best explains the purpose of marking a method as nonisolated inside a Swift actor?
ATo allow the method to modify actor-isolated state without synchronization.
BTo make the method asynchronous and require awaiting before calling.
CTo allow the method to be called synchronously without actor isolation, typically for stateless or thread-safe operations.
DTo prevent the method from being called outside the actor's context.
Attempts:
2 left
💡 Hint
Think about when you want to avoid the overhead of actor isolation.

Practice

(1/5)
1. What is the main purpose of marking a method as nonisolated in a Swift actor?
easy
A. To allow the method to run outside the actor's isolation without needing await
B. To make the method private to the actor
C. To force the method to always run asynchronously
D. To prevent the method from accessing any properties

Solution

  1. Step 1: Understand actor isolation

    Actors protect their data by isolating it, so methods usually run inside this isolation.
  2. Step 2: Role of nonisolated

    Marking a method nonisolated means it runs outside this isolation and can be called without await.
  3. Final Answer:

    To allow the method to run outside the actor's isolation without needing await -> Option A
  4. Quick Check:

    Nonisolated method = runs outside isolation without await [OK]
Hint: Nonisolated means no await needed to call method [OK]
Common Mistakes:
  • Thinking nonisolated methods are private
  • Assuming nonisolated methods must be async
  • Believing nonisolated methods cannot access any properties
2. Which of the following is the correct way to declare a nonisolated method inside a Swift actor?
easy
A. func nonisolated greet() { print("Hello") }
B. nonisolated func greet() { print("Hello") }
C. func greet() nonisolated { print("Hello") }
D. func greet() async nonisolated { print("Hello") }

Solution

  1. Step 1: Recall correct syntax for nonisolated

    The nonisolated keyword comes before func in the method declaration.
  2. Step 2: Check each option

    nonisolated func greet() { print("Hello") } correctly places nonisolated before func. Others place it incorrectly or add unnecessary keywords.
  3. Final Answer:

    nonisolated func greet() { print("Hello") } -> Option B
  4. Quick Check:

    Keyword nonisolated before func = correct syntax [OK]
Hint: Put nonisolated before func keyword [OK]
Common Mistakes:
  • Placing nonisolated after func
  • Adding async unnecessarily
  • Using nonisolated as a function modifier
3. What will be the output of the following Swift code?
actor Counter {
    var count = 0
    nonisolated func printHello() {
        print("Hello")
    }
    func increment() {
        count += 1
    }
}

let counter = Counter()
counter.printHello()
// counter.increment() // requires await
medium
A. Compile error because printHello is nonisolated
B. Hello\n1
C. Hello
D. Runtime error because increment is not awaited

Solution

  1. Step 1: Understand nonisolated method call

    The method printHello() is marked nonisolated, so it can be called directly without await.
  2. Step 2: Analyze output

    Calling counter.printHello() prints "Hello". The increment method is commented out, so no other output.
  3. Final Answer:

    Hello -> Option C
  4. Quick Check:

    Nonisolated method prints Hello directly [OK]
Hint: Nonisolated methods run without await and print output [OK]
Common Mistakes:
  • Expecting increment output without await
  • Thinking nonisolated causes compile error
  • Confusing runtime error with compile error
4. Consider this Swift actor code snippet:
actor Logger {
    var logs = [String]()
    nonisolated func printLog(_ message: String) {
        print(message)
    }
    func addLog(_ message: String) {
        logs.append(message)
    }
}

let logger = Logger()
logger.printLog("Start")
logger.addLog("Start")

What is the main issue with this code?
medium
A. addLog method must be marked nonisolated
B. Nonisolated method printLog cannot access actor's logs array
C. Nonisolated method printLog causes data race on logs
D. Cannot call addLog without await, causing a compile error

Solution

  1. Step 1: Check method calls

    The addLog method is isolated and must be called with await outside the actor.
  2. Step 2: Identify error

    Calling logger.addLog("Start") without await causes a compile error.
  3. Final Answer:

    Cannot call addLog without await, causing a compile error -> Option D
  4. Quick Check:

    Isolated method call requires await [OK]
Hint: Isolated methods need await; nonisolated do not [OK]
Common Mistakes:
  • Thinking nonisolated can access isolated properties
  • Assuming addLog can be called without await
  • Marking all methods nonisolated incorrectly
5. You want to add a nonisolated method to a Swift actor that returns a constant string without accessing any actor-isolated data. Which of the following implementations is correct and safe?
hard
A. nonisolated func status() -> String { return "Ready" }
B. nonisolated func status() -> String { return logs.first ?? "Ready" }
C. func status() async -> String { return "Ready" }
D. func status() -> String { return "Ready" }

Solution

  1. Step 1: Identify safe nonisolated method

    A nonisolated method must not access actor-isolated data like logs.
  2. Step 2: Evaluate options

    nonisolated func status() -> String { return "Ready" } returns a constant string without accessing isolated data, so it's safe and correct.
  3. Final Answer:

    nonisolated func status() -> String { return "Ready" } -> Option A
  4. Quick Check:

    Nonisolated method returns constant, no isolated data access [OK]
Hint: Nonisolated methods must avoid actor-isolated data [OK]
Common Mistakes:
  • Accessing isolated properties inside nonisolated methods
  • Making nonisolated methods async unnecessarily
  • Ignoring actor isolation rules
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