Why this happens
Objective-C’s @synchronized(self) { … } gave a quick, per-object mutex. Swift deliberately omitted a direct equivalent because the language now centers on structured concurrency and data-race safety. The compiler can enforce isolation when you model shared mutable state inside an actor, eliminating whole classes of races at build time instead of runtime.
If you are migrating Objective-C code or writing new concurrent Swift, you need a replacement that fits the concurrency model you are targeting: async/await (actors), synchronous callbacks (GCD serial queue), or high-contention hot paths (locks).
How to fix it
1. Use actors — the modern, recommended approach
Actors are reference types that serialize all access to their mutable state. Only one task can execute inside an actor at a time, and the compiler forces callers to await every access.
actor TemperatureLogger {
let label: String
private var measurements: [Int] = []
private(set) var max: Int = Int.min
init(label: String) {
self.label = label
}
func record(_ value: Int) {
measurements.append(value)
if value > max { max = value }
}
func snapshot() -> (count: Int, max: Int) {
(measurements.count, max)
}
}
// Usage from any task
let logger = TemperatureLogger(label: "CPU")
Task { await logger.record(42) }
let stats = await logger.snapshot()
Why this wins:
– Compile-time guarantee: you cannot forget to await.
– No manual lock/unlock — the actor’s executor handles serialization.
– Works naturally with async/await and Task groups.
2. GCD serial queue — for non-async callback code
When you cannot make the call site async (e.g., inside a synchronous delegate or C callback), a private serial DispatchQueue reproduces the old @synchronized semantics.
final class LegacyCache {
private var storage: [String: Data] = [:]
private let queue = DispatchQueue(label: "com.example.LegacyCache")
func set(_ data: Data, forKey key: String) {
queue.sync { storage[key] = data }
}
func object(forKey key: String) -> Data? {
queue.sync { storage[key] }
}
}
sync blocks the caller until the block finishes, exactly like @synchronized. Use a unique label per instance to avoid cross-instance contention.
3. NSLock / os_unfair_lock — when microseconds matter
For extremely hot paths where even actor hopping or GCD overhead is measurable, a lightweight lock is faster. NSLock is the safe, portable choice; os_unfair_lock is faster but requires manual memory management and must never be held across await.
final class FastCounter {
private var value = 0
private let lock = NSLock()
func increment() -> Int {
lock.lock()
defer { lock.unlock() }
value += 1
return value
}
}
Rules of thumb:
– Default to NSLock.
– Only reach for os_unfair_lock after profiling proves contention.
– Never call await or blocking APIs while the lock is held.
4. Reduce synchronization with value types and Sendable
The best lock is the one you don’t need. Swift’s copy-on-write value types (struct, enum, Array, Dictionary) give each thread its own copy automatically. Mark types Sendable when they cross concurrency domains; the compiler will verify they contain no mutable reference semantics.
struct Reading: Sendable { // immutable → thread-safe by design
let timestamp: Date
let value: Double
}
How to prevent it
- Start new modules with actors — they are the default synchronization primitive in Swift 6.
- Prefer
letovervarand value types over reference types. - Conform to
Sendableexplicitly; the compiler catches accidental captures. - Avoid recursive locks (
NSRecursiveLock) — they mask design problems. - Profile before optimizing — actors and GCD are fast enough for 99 % of cases.
FAQ
Can I still use @synchronized in Swift via Objective-C bridging?
No. @synchronized is an Objective-C compiler directive; it does not exist in Swift and cannot be imported. Wrap the Objective-C class in a Swift actor or GCD queue instead.
Are actors slower than NSLock?
In uncontended cases the difference is nanoseconds. Under contention actors avoid priority inversion and thread explosion better than raw locks. Measure with Instruments before assuming locks are necessary.
How do I migrate a large @synchronized codebase incrementally?
Wrap each legacy class in a private actor or serial queue, then migrate call sites to async one by one. The boundary stays synchronous (queue.sync or await on a non-isolated actor method) until the whole graph is async.
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.