Member-only story

Debugging SwiftUI’s Entry Macro

The new way isn’t quite like the old way. And that was a problem.

Michael Long
6 min readFeb 5, 2025
Image via DALL-E

If you’ve ever created your own Environment variables in SwiftUI you know that you have to generate a bit of boilerplate code to do so.

We need to define an EnvironmentKey with a defaultValue for that key, and then we need to extend EnvironmentValues with a getter/setter pair for that value.

Here’s some code that defines a new Navigator environment variable for my new SwiftUI open source library, Navigator.

// key with default value
private struct NavigatorKey: EnvironmentKey {
static let defaultValue: Navigator = Navigator(owner: .default)
}

// getter/setter pair
extension EnvironmentValues {
public var navigator: Navigator {
get { self[NavigatorKey.self] }
set { self[NavigatorKey.self] = newValue }
}
}

You’ve seen it before. It’s fairly straightforward, but it’s also code one needs to write for each and every environment value we want to create. There should be a better way.

Swift Macros

Turns out there is. The “@Entry” macro in SwiftUI was announced during WWDC 2024, based on the Swift Macros feature introduced as part of Swift 5.9.

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

Responses (3)