Skip to content

Instantly share code, notes, and snippets.

@simonnickel
Created October 22, 2024 20:57
Show Gist options
  • Save simonnickel/4d8d1ffd3f5d98482fbc293b0a11b8a1 to your computer and use it in GitHub Desktop.
Save simonnickel/4d8d1ffd3f5d98482fbc293b0a11b8a1 to your computer and use it in GitHub Desktop.
Swift Actor - later accesses could race
actor SomeActor {
func doSomething() { }
}
class SomeClass {
private let someActor = SomeActor()
func doSomething() {
Task { // Task-isolated value of type '() async -> ()' passed as a strongly transferred parameter; later accesses could race
await someActor.doSomething()
}
}
func doSomething() async {
await someActor.doSomething()
}
}
@mattmassicotte
Copy link

This is tricky because the compiler error is really unhelpful. Here's what's going on:

Task {
	await someActor.doSomething()
}

this is actually:

Task {
	// note the self!
	await self.someActor.doSomething()
}

You are catpuring self in a non-isolated task, but self (SomeClass) is not Sendable! Even this will not work.

Task {
	print(self)
}

To do what you want, to have to avoid the self capture. Perhaps like this:

func doSomething() {
	Task { [someActor] in
		await someActor.doSomething()
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment