when to use nonisolated

Generated on 10/24/2024

1 search

In Swift, the nonisolated keyword is used to indicate that a method or property is not isolated to a specific actor, even if it belongs to a type that is otherwise actor-isolated. This can be useful in scenarios where you have callbacks or methods that do not make any guarantees about the context in which they are called back.

For example, if you have a method on a type that is isolated to the main actor, but you want this specific method to be callable from any context without isolation, you can declare it as nonisolated. This is particularly useful for callbacks that intentionally do not specify where they will be called from, allowing them to be used in a more flexible manner.

However, using nonisolated comes with the responsibility of ensuring that the method or property is used safely, as it bypasses the usual actor isolation guarantees provided by Swift's concurrency model. It is generally recommended to use Swift's compile-time guarantees whenever possible, and resort to nonisolated only when necessary.

For more detailed information, you can refer to the session Migrate your app to Swift 6 (21:33) from WWDC 2024, which discusses the use of nonisolated in the context of Swift concurrency.