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
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.
About This Article
Thumbtack's iOS team found that the standard 'flag and check' pattern for running code once has real problems. It doesn't separate logic from state well, it breaks easily if someone changes it by accident, and it gets messy when many engineers use it across a large codebase.
Daniel Roth's team built a top-level function using Objective-C runtime functions (objc_setAssociatedObject and objc_getAssociatedObject) and Swift source code literals (#fileId, #line, #column). This function tracks execution state with a unique identifier, so developers don't need to manage separate instance variables.
Swift-RunOnce changed one-time code execution from something that 'shouldn't fail' to something that 'can't fail.' It removes an entire class of bugs by keeping state internal and locked away from outside changes. The solution stays thread-safe and handles reentrancy across the application.