iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😳

Non-Sendable Types Crossing Actor Boundaries: Region-Based Isolation in Swift 6

に公開
2024/07/08

In Swift 6, a new behavior called Region-based Isolation has been introduced.
This provides a unique behavior where even non-Sendable types can cross actor boundaries.

How It Used to Be

When Strict Concurrency is enabled in a Swift 5 environment, the following code will trigger a warning.
Take a close look and try to guess where the warning might appear.

func updateView(view: ComplexLayoutView) async {
    // Function not isolated to any actor
    let layout = ComplexLayout.calculate()
    await view.apply(layout)
}

// Non Sendable
class ComplexLayout {
    // ...(Properties for layout information)

    static func calculate() -> ComplexLayout {
        //...(Layout calculation)
        return ComplexLayout()
    }
}

@MainActor
class ComplexLayoutView {
    func apply(_ layout: ComplexLayout) {
        // Update layout based on argument information
    }
}

The answer is here.

func updateView(view: ComplexLayoutView) async {
    // Function not isolated to any actor
    let layout = ComplexLayout.calculate()
    await view.apply(layout) // ⚠️ Passing argument of non-sendable type ...
}

The content of the warning is as follows:

Passing argument of non-sendable type 'ComplexLayout' into main actor-isolated context may introduce data races

In other words, the non-Sendable layout created within updateView (which is not isolated to any actor) is being shared with ComplexLayoutView (which is isolated to the MainActor), potentially causing a data race.

But does this really cause a data race?
A data race occurs when there is simultaneous access from multiple threads.
However, in the updateView code above, layout is created, passed to the apply function, and then never touched again within updateView.
In this case, once the layout is passed to the MainActor, it won't be accessed by any other actor, meaning it won't cause a data race.

Region-based Isolation was introduced to handle cases like this.

What Happens from Swift 6

The code above can be built without warnings.

However, this only applies to cases where it can be guaranteed that the object will not be accessed simultaneously.
The following code will result in an error (or warning):

class ComplexLayout {
    // ..
    func printInformation() { ... }
} 

func updateView(view: ComplexLayoutView) async {
    let layout = ComplexLayout.calculate()
    await view.apply(layout) // ⚠️ Passing argument of non-sendable type ...
    layout.printInformation()
}

This is because after passing layout to the MainActor, layout is accessed again within updateView.
Since the possibility of simultaneous access from multiple threads remains, the compiler points this out.

The sending Keyword

The sending Keyword for Arguments

In the example above, layout was created inside the function.
If it is passed as an argument, a warning will appear because the caller function might continue to access layout.

func updateView(view: ComplexLayoutView, with layout: ComplexLayout) async {
    await view.apply(layout) // ⚠️ Passing argument of non-sendable type ...
}

In such cases, you can avoid this by adding the sending keyword to the argument.
This sending indicates that the object is being passed to another actor.
The following code does not produce any warnings:

func updateView(view: ComplexLayoutView, with layout: sending ComplexLayout) async {
    await view.apply(layout)
}

func anotherFunction() async {
    let view = ComplexLayoutView()
    let layout = ComplexLayout.calculate()
    await updateView(view: view, layout: layout)
}

However, if you access layout after updateView, a warning will appear.
This is because you are still accessing layout after it has been passed to another actor inside updateView.

func anotherFunction() async {
    let view = ComplexLayoutView()
    let layout = ComplexLayout.calculate()
    await updateView(view: view, layout: layout) // ⚠️ Sending 'layout' risks causing data races...
    layout.printInformation()
}

The sending Keyword for Return Values

This sending keyword can also be applied to the return type of a function.
When applied to a function's return value, it indicates that the return value is not being accessed from anywhere else.

The following calculate function is fine, but the calculateWithCache function will result in a warning.
This is because, while the returned ComplexLayout might be passed to another actor, it has been captured as a cache, leaving the possibility that it could be accessed from other threads.

class ComplexLayoutLayout {
    static func calculate() -> sending ComplexLayout {
        ComplexLayout()
    }

    @FooActor private static var cache: ComplexLayout?

    @FooActor static func calculateWithCache() -> sending ComplexLayout {
        if let cache {
            return cache
        }
        let layout = ComplexLayout()
        cache = layout
        return layout
    } // ⚠️ Sending 'layout' risks causing data races...
}

Situation in Xcode 16 Beta 2

Unfortunately, in Xcode 16 Beta 2, which is the latest version at the time of writing, this feature does not seem to work for Task.

Therefore, the following code will trigger a warning.

let layout = ComplexLayout.calculate()
Task { @MainActor in
    view.apply(layout)
}

However, it seems a PR was merged recently to make this work correctly for Task as well, so we can expect it to be included in the next Beta or the official release of Xcode 16.
https://github.com/swiftlang/swift/pull/74608

Conclusion

I have introduced Region-based Isolation, which is enabled in Swift 6.
For details on how this works and its specific behavior, please refer to SE-414.
However, since it is a complex topic and the proposal itself mentions that "developers do not need to understand its detailed behavior," I do not think there is a need to force yourself to follow it too closely.

References

Discussion