Junior — Middle
What types of atomic operations are you aware of in Swift?
sobes.tech AI
Answer from AI
In Swift, atomic operations are usually associated with safe access to shared resources in a multithreaded environment. The language itself does not provide built-in atomic primitives, but you can use:
- DispatchQueue with synchronization via
syncorasyncfor sequential access. - OSAtomic functions (deprecated, not recommended).
- stdatomic.h from C11 for atomic operations at the C level.
- NSLock, NSRecursiveLock, and other locking objects to protect critical sections.
- In Swift 5.5+, you can use
@Sendableandactorfor safe state management.
Example of an atomic increment using DispatchQueue:
class AtomicCounter {
private var value = 0
private let queue = DispatchQueue(label: "atomic.counter.queue")
func increment() {
queue.sync {
value += 1
}
}
func get() -> Int {
return queue.sync { value }
}
}
Thus, atomic operations in Swift are implemented through synchronization and locking, rather than built-in atomic primitives.