Swift Atomics Library
Article Summary
Karoy Lorentey from Apple just dropped Swift Atomics, bringing C/C++ style low-level atomic operations directly into Swift. This changes the game for systems programmers who've been blocked from building concurrent data structures in pure Swift.
Apple's Swift team released an open source package enabling atomic operations in Swift code, based on the recently accepted SE-0282 proposal. The library provides the foundation for building synchronization constructs and concurrent data structures without resorting to other languages.
Key Takeaways
- Supports atomic operations on integers, booleans, pointers, and class references
- Two wrappers: ManagedAtomic (memory safe) and UnsafeAtomic (flexible, manual management)
- All operations guaranteed lock-free, mapping to dedicated CPU instructions where available
- Atomic strong references enable memory reclamation fitting Swift's reference counting model
- Use sparingly: isolate to small units and apply Thread Sanitizer liberally
Critical Insight
Swift developers can now build concurrent data structures in pure Swift using carefully designed atomic APIs that were previously only accessible through C/C++.