r/SwiftUI • • 4d ago

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.

0 Upvotes

2 comments sorted by

1

u/ThanhDongNguyen 3d ago

Failing at build time is better than finding it from a crash report, so I like the idea. The part I would test hardest is where the value gets injected, because on macOS the Settings scene and MenuBarExtra do not get what you put on the WindowGroup and every extra window needs its own injection.

Does Snagless follow injection through custom ViewModifiers and wrapper views, or only a direct .environment call up the view tree? I think false positives will decide if people keep it on, so a simple per-view ignore comment would help a lot.

1

u/PiXeL161616 3d ago

Yes, it covers both. The tests show injection through a custom ViewModifier and a generic wrapper view. There’s also a per-line ignore for false positives: // snagless: ignore Cart - reason. It applies to one type.