Whats the best way to convert a static let property into something swift concurrency / 6 is happy with

Asked on 08/05/2024

1 search

To convert a static let property into something that is compatible with Swift concurrency and Swift 6, you have several options depending on your specific needs and constraints. Here are some approaches discussed in the WWDC sessions:

  1. Use let for Immutability:

    • If the property does not need to be mutable, simply keeping it as a let is the best option. This ensures that the property is immutable and cannot cause data races when accessed from multiple threads.
    • Migrate your app to Swift 6
  2. Annotate with @MainActor:

    • If the property needs to be mutable and is used in the UI layer, you can tie it to the main actor by annotating it with @MainActor. This ensures that all accesses to the property are made on the main thread.
    • Migrate your app to Swift 6
  3. Use nonisolated unsafe:

    • As a last resort, if you have an external mechanism ensuring the safety of the property (e.g., using a dispatch queue), you can mark it as nonisolated unsafe. This puts the burden on you to ensure the safety of the variable.
    • Migrate your app to Swift 6
  4. Atomic Values:

    • For low-level synchronization, you can use atomic values. These should be stored in let properties for safe concurrent access. All operations on atomics are explicit with memory ordering arguments.
    • What’s new in Swift

By following these guidelines, you can ensure that your static let properties are compatible with Swift concurrency and Swift 6, providing data-race safety and improving the overall correctness of your code.