New in SwiftUI: the macro @Entry


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


If you write apps with SwiftUI, you’ve probably used the Environment to inject values into the view hierarchy.

And you probably also had to create your own EnvironmentKey and EnvironmentValues property, in order to store custom values into the Environment.

And I’m sure you’ve felt that all the code you had to write was really the kind of boilerplate that any engineer would love to automatically generate!

Well the good news is that since Xcode 16 it’s now become possible to very easily generate that code!

Now you no longer need to explicitly create an EnvironmentKey and then use it to implement a new computed property of EnvironmentValues.

Instead you can simply declare an extension to EnvironmentValues, declare your property, give it a default value and, finally, annotate it with the new @Entry macro.

And if we expand the macro to see what code it generates, we’ll see that it produces the exact same code than we had to write by hand before 👌

Even better: since the code is generated at compile time, this macro has no requirement for a minimum version of iOS!

And by the way, this macro is not limited to EnvironmentValues: there are some other contexts where it can also be used, make sure you read the documentation to find out about them!

That’s all for this article, I hope that you’ve enjoyed learning about this new feature of SwiftUI!

Here’s the code if you want to experiment with it:

// Before
import SwiftUI

struct CustomColorEnvironmentKey: EnvironmentKey {
    static var defaultValue: Color = .white
}

extension EnvironmentValues {
    var customColor: Color {
        get {
            self[CustomColorEnvironmentKey.self]
        }

        set {
            self[CustomColorEnvironmentKey.self] = newValue
        }
    }
}

// After
import SwiftUI

extension EnvironmentValues {
    @Entry var customColor: Color = .white
}
Next
Next

How to get started with Swift Testing