Swift Actor Isolation
The nonisolated mark takes a member of an actor outside its isolation. A member with that mark can be reached without await when it never touches changing actor state.
A nonisolated constant
The name constant carries the nonisolated mark, so the first print reads it directly. The wins count stays isolated, and its changes and its read carry await.
actor Team {
nonisolated let name = "Falcons"
var wins = 0
func addWin() {
wins += 1
}
func readWins() -> Int {
wins
}
}
let team = Team()
print(team.name)
await team.addWin()
await team.addWin()
let wins = await team.readWins()
print(wins)A nonisolated method
The scale method carries the nonisolated mark and reads only the factor constant. The scale call prints 42 without await, while the record call still carries await.
actor Converter {
nonisolated let factor = 2
var calls = 0
nonisolated func scale(value: Int) -> Int {
value * factor
}
func record() {
calls += 1
}
func readCalls() -> Int {
calls
}
}
let converter = Converter()
print(converter.scale(value: 21))
await converter.record()
let calls = await converter.readCalls()
print(calls)An isolated count beside a plain title
The title constant is nonisolated and prints without await. The songs count is isolated, so three add calls and one read call each carry await.
actor Playlist {
nonisolated let title = "Morning"
var songs = 0
func addSong() {
songs += 1
}
func count() -> Int {
songs
}
}
let list = Playlist()
print(list.title)
await list.addSong()
await list.addSong()
await list.addSong()
let total = await list.count()
print(total)Example
actor Library {
nonisolated let branch = "Central"
var books = 0
func addBook() {
books += 1
}
func total() -> Int {
books
}
}
let library = Library()
print(library.branch)
await library.addBook()
await library.addBook()
let books = await library.total()
print(books)Key points
- The nonisolated mark sits before the member it covers.
- A constant declared with let inside an actor never changes after creation.
- A nonisolated let constant can be read from outside without await.
- A nonisolated method can use constants and its own parameters.
- A nonisolated method cannot read or change isolated stored variables.
- Stored variables without the mark stay isolated and need await from outside.
In this example, the branch constant is nonisolated, so the first print reads it without await. The books count stays isolated, and two add calls raise it through await. The final awaited read prints 2.
Note
Marking one member nonisolated leaves the rest of the actor isolated.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which member can be read from outside an actor without await?