Nonisolated methods let you run code without waiting for other tasks. They help when you want to do simple things fast without blocking others.
0
0
Nonisolated methods in Swift
Introduction
When you want to read data that doesn't change and is safe to access anytime.
When you need to provide quick answers without waiting for other tasks.
When you want to avoid delays in your program by not locking resources.
When you have simple helper functions that don't touch shared data.
When you want to improve app speed by running some methods outside isolation.
Syntax
Swift
nonisolated func methodName() { // code here }
The nonisolated keyword tells Swift this method can run without isolation.
Use it only when the method does not access or change shared data.
Examples
This method can be called without waiting for the actor's isolation.
Swift
actor MyActor {
nonisolated func greet() {
print("Hello from nonisolated method!")
}
}The
description method does not access count, so it can be nonisolated.Swift
actor Counter {
var count = 0
nonisolated func description() -> String {
return "Counter actor"
}
}Sample Program
This program shows a Logger actor with a nonisolated method logStart and an isolated method logMessage. You can call logStart directly without await, but you must use await for logMessage.
Swift
actor Logger {
nonisolated func logStart() {
print("Starting...")
}
func logMessage(_ message: String) {
print("Log: \(message)")
}
}
let logger = Logger()
// Call nonisolated method without await
logger.logStart()
// Call isolated method with await
Task {
await logger.logMessage("Hello")
}OutputSuccess
Important Notes
Nonisolated methods cannot access or change actor's isolated data safely.
Use nonisolated only for read-only or independent code.
Calling isolated methods requires await, but nonisolated methods do not.
Summary
Nonisolated methods run outside actor isolation.
They are useful for simple, safe code that doesn't touch shared data.
Nonisolated methods can be called without await.