Thumbtack Daniel Roth Dec 22, 2021

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

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.

The article reveals why even Swift's lazy var syntax fails the thread-safety test and how the team worked around fundamental language limitations.

About This Article

Problem

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.

Solution

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.

Impact

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.