r/iOSProgramming • u/V0RT3X_L33T_ • 3d ago
Article Open-sourced Snagless: SwiftUI @Environment crashes caught at build time, using SwiftSyntax
Our codebase has hundreds of `@Environment` call sites. Any one of them can crash in production with "No Observable object of type X found" if a view gets shown without the value injected somewhere above it, and the compiler can't see it. Every fix I found started with "first, change all your call sites."
So I built Snagless, a SwiftPM/Xcode build plugin. It reads your SwiftUI source with SwiftSyntax, works out which view shows which across modules, and fails the build when a view can appear without a value it needs. Zero code changes, about 90 ms on a 431-file app.
Built with Claude Code, and the write-up is upfront about every time the AI was wrong and what caught it.
Write-up: https://tarek-builds.dev/p/swiftui-environment-crashes-compile-just-fine-so-i-made-them-fail-the-build/
Repo: https://github.com/tareksabry1337/snagless
Happy to answer questions.
1
u/Neat_Area_4781 3d ago
The cross-module part is what caught my eye. How does it handle views that are only reachable through a closure or custom container, where the environment injection is conditional? That seems like the tricky edge: missing a path that can crash, or flagging one that's safe.
1
u/jaymakesapps 3d ago
every fix starting with "first, change all your call sites" is exactly why nobody fixes this until it crashes in prod. 90ms on 431 files is basically free
1
u/dawedev 3d ago
Curious how it treats views hosted from UIKit through UIHostingController, where the environment gets injected on the host's rootView instead of a parent view. Does that count as a valid injection path or does it flag them?
1
u/DimensionMindless336 20h ago
The "fail the build" part is the tricky bit, and it's not the analysis that gets you -- it's making the plugin reliable enough that people don't mute it.
Two things that bit me shipping a SwiftSyntax-based build plugin:
One more for the README: concurrent agents or worktrees sharing one DerivedData will stomp the clang module cache, and the resulting nonsense errors look exactly like your analyzer's fault. One DerivedData per worktree. 90ms on 431 files is genuinely impressive -- just don't let a CI hiccup make people blame the tool.
1
u/[deleted] 3d ago
[removed] — view removed comment