Introducing Swift RunOnce
Article Summary
Daniel Roth from Thumbtack's iOS team just solved a problem every Swift developer has faced: ensuring code runs exactly once without the brittle boolean flags that break at scale.
Thumbtack Engineering open-sourced Swift-RunOnce, a thread-safe utility that eliminates an entire category of bugs around one-time code execution. The solution uses Objective-C runtime hacks and Swift's literal expressions to create truly declarative, inline one-time code blocks that can't be invalidated.
Key Takeaways
- Traditional boolean flag approach fails at scale with multiple engineers working in parallel
- Solution uses objc_setAssociatedObject and source code location (#fileId, #line, #column) as unique identifiers
- Thread-safe, reentrant implementation completely hides state from developers
- Enables trailing closure syntax: self.runOnce { /* code here */ }
- Available on GitHub under Apache 2.0 license
Critical Insight
Swift-RunOnce replaces a pattern that shouldn't fail with one that can't fail, using runtime hacks to make one-time code both declarative and bulletproof.