Pick the fix
func tap() { counter.increment() } fails: actor-isolated method can't be called from a nonisolated context. Which fix is right?
actor Counter {
private(set) var value = 0
func increment() { value += 1 }
}
let counter = Counter()
func tap() { counter.increment() }Hint 1 of 2
What does a caller outside the actor have to do?
Hint 2 of 2
What does nonisolated give up?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Make tap() async and write await counter.increment()
Correct. Calls from outside the actor must await their turn.
Why not the others?
- B Mark
increment()asnonisolated. A nonisolated method can't mutatevalue, so this doesn't compile either. - C Write
counter.value += 1directly.valueis isolated too, so this fails in the same way. - D Turn Counter into a class marked
@unchecked Sendable. It compiles, but you have removed the protection and created a data race.