r/iOSProgramming • • 3h 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 Upvotes

5 comments sorted by

1

u/Neat_Area_4781 1h 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/V0RT3X_L33T_ 1h ago

It reads each file on its own first: which views it declares, which `@Environment` values each one needs, which views it shows, where .environment(...) is called, and what the file imports. Then it connects everything across files and modules. If two modules have a view with the same name, the file's imports decide which one is meant, and if they can't, it checks against both. After that, modules don't matter: if a view in a package needs a Cart, that need follows it up through every app view that shows it, until something provides a Cart or it reaches the App or a preview.

For conditional injection, each branch counts on its own, so if flag { Child().environment(cart) } else { Child() } gets flagged. The one miss is a value provided under #if: it counts as provided in every build. That's the one crashing case it misses today, and it's first on the roadmap.

1

u/jaymakesapps 1h 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

•

u/V0RT3X_L33T_ 59m ago

Right, that's what pushed me to build this tbh, with AI it was pretty much just "I'll let Claude do it while I'm sleeping" and it did work lol

•

u/dawedev 5m 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?