Static property is not concurrency-safe: Is there an easy solution?

Static mutable properties are generally not safe because they can be concurrently modified from any thread/actor, and this is what the compiler error is trying to communitate. There are multiple ways to fix this:

  • If you don't even need to write to wName, make it a static let instead of static var.
  • If you still need to mutate it occasionally, wrap it into a Mutex (the new concurrency primitive available in the Standard Library with Swift 6.0 and the newest Apple OS releases) or e.g. OSAllocatedUnfairLock for former Apple OS versions.
  • Make MBackup an actor, the static property will become isolated to it.
  • Constrain it to some global actor, perhaps alongside with the whole MBackup class that needs to access it. This way, all reads and writes to it will be serialized.
  • Make it nonisolated(unsafe). If it's only accessed from the MBackup class, and you can make sure by other means that all accesses are serialized, you can simply tell the compiler to ignore the concurrency-safety in this instance. It'd also help to perhaps make it private so that you don't accidentally access it from outside. This fix is typically the last resort, though.

The first two and the last options lean more in the direction of not requiring a complete app rework.

9 Likes