FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

How to make function parameters isolated

Paul Hudson    @twostraws   

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>()

func debugLog(dataStore: isolated DataStore) {
    print("Username: \(dataStore.username)")
    print("Friends: \(dataStore.friends)")
    print("High scores: \(dataStore.highScores)")
    print("Favorites: \(dataStore.favorites)")

That creates a DataStore actor with various properties, 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 pushing that access out by a level, because now the whole function must be run on that actor rather than just individual lines inside it.

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?

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.