Adding values to the SwiftUI environment with Xcode 16’s Entry macro

Published on: July 15, 2024

Adding custom values to SwiftUI’s environment has never been very hard to do to. However, the syntax for doing it is verbose and easy to forget. To refresh your mind, take a look at this post where I explain how to add your own environment values to a SwiftUI view.

To summarize what’s shown in that post; here’s how you add a custom value to the environment using Xcode 15 and earlier:

private struct DateFormatterKey: EnvironmentKey {
    static let defaultValue: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "MM/dd/yyyy"
        return formatter
    }()
}

extension EnvironmentValues {
    var dateFormatter: DateFormatter {
        get { self[DateFormatterKey.self] }
        set { self[DateFormatterKey.self] = newValue }
    }
}

We have to define an environment key, define a default value, and write a getter and setter to retrieve our value from the environment using our key.

This is repetitive, easy to forget, and just annoying to do.

If you prefer learning thorugh video, here's the video to watch:

Luckily, in Xcode 16 we have access to the @Entry macro. This macro allows us to define the exact same environment key like this:

extension EnvironmentValues {
    @Entry var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "MM/dd/yyyy"
        return formatter
    }()
}

All we have to define now is a variable that’s annotated with @Entry and we’re done.

The property name is used as the environment key so in this case we’d set our date formatter like this:

myView
    .environment(\.dateFormatter, Dateformatter())

I absolutely love this new syntax because it gets rid of all the boilerplate in one go.

And the best part of this macro?

We can use it in projects that target iOS versions older than 18! So as soon as you start developing your project with Xcode 16 you’ll be able to use this macro regardless of your deployment target.

Categories

SwiftUI

Subscribe to my newsletter