How to use strict concurrency

Generated on 8/12/2024

1 search

To use strict concurrency in Swift 6, you can follow these steps as outlined in the session "Migrate your app to Swift 6" from WWDC 2024:

  1. Enable Strict Concurrency Checking: Start by enabling strict concurrency checking in your project's build settings. This will opt your entire module into being checked for possible race conditions. It's often recommended to start with simpler targets, such as UI layers, which typically run on the main thread and use APIs that are concurrency-safe.

  2. Address Compiler Warnings: Once strict concurrency checking is enabled, the Swift compiler will emit warnings about code that may not be concurrency-safe. These warnings are crucial for identifying potential data races in your code. You should methodically address these warnings to ensure your code is safe for concurrent execution.

  3. Adopt Swift 6 Language Mode: Swift 6 introduces data race safety by default, turning potential data race issues into compile-time errors. This significantly improves the security and reliability of your app. You can adopt Swift 6 language mode module by module, allowing for a gradual transition.

  4. Use Concurrency Features: Leverage Swift's concurrency features such as actors for protecting mutable state and the Sendable protocol for safe data sharing. These features help in achieving data isolation and preventing data races.

  5. Incremental Migration: If your project generates a large number of warnings, focus on quick wins by making simple changes, such as marking methods with the @MainActor attribute or making global variables immutable. This can quickly reduce the number of warnings.

For a detailed walkthrough, you can refer to the session Migrate your app to Swift 6 (11:05) which covers enabling complete checking in the watch extension, and Migrate your app to Swift 6 (27:24) for enabling complete checking in CoffeeKit.