How to make function parameters isolated
How to make function parameters isolated 관련
Updated for Xcode 15
Any properties and methods that belong to an actor are isolated to that actor, but you can make external functions isolated to an actor if you want. This allows the function to access actor-isolated state as if it were inside that actor, without needing to use await
.
Here’s a simple example so you can see what I mean:
actor DataStore {
var username = "Anonymous"
var friends = [String]()
var highScores = [Int]()
var favorites = Set<Int>()
init() {
// load data here
}
func save() {
// save data here
}
}
func debugLog(dataStore: isolated DataStore) {
print("Username: \(dataStore.username)")
print("Friends: \(dataStore.friends)")
print("High scores: \(dataStore.highScores)")
print("Favorites: \(dataStore.favorites)")
}
let data = DataStore()
await debugLog(dataStore: data)
That creates a DataStore
actor with various properties plus a couple of placeholder methods, then creates a debugLog()
method that prints those without using await
– they can be accessed directly. Notice the addition of the isolated
keyword in the function signature; that’s what allows this direct access, and it even allows the function to write to those properties too.
Using isolated
like this does not bypass any of the underlying safety or implementation of actors – there can still only be one thread accessing the actor at any one time. What we’ve done just pushes that access out by a level, because now the whole function must be run on that actor rather than just individual lines inside it. In practice, this means debugLog(dataStore:)
needs to be called using await
.
This approach has an important side effect: because the whole function is now isolated to the actor, it must be called using await
even though it isn’t marked as async. This makes the function itself a single potential suspension point rather than individual accesses to the actor being suspension points.
In case you were wondering, you can’t have two isolation parameters, because it wouldn’t really make sense – which one is executing the function?