Simplify your code with @Entry
The Swift macro to reduce boilerplate
If you’ve ever tried to tap into the systems provided by SwiftUI, you are very likely to have come across code like this:
struct MyEnvironmentKey: EnvironmentKey {
static let defaultValue: Int? = nil
}
extension EnvironmentValues {
var myEnvironmentValue: Int? {
get { self[MyEnvironmentKey.self] }
set { self[MyEnvironmentKey.self] = newValue }
}
}
This code may seem all right, but if you ever had to add multiple values to the environment, you quickly realised how fast you can fill your codebase with a lot of boilerplate code. Let’s see how to simplify this!
@Entry to the rescue
Starting with iOS 13, we can replace the code above with 3 simple lines.
extension EnvironmentValues {
@Entry var myEnvironmentValue: Int? = nil
}
After creating an extension for EnvironmentValues
you can declare your property as if it was a regular stored property, except it has to be annotated with the @Entry
macro. Under the hood this macro generates the necessary code but your codebase is a lot simple.
What else can it do?
The @Entry
macro can be used to extend not only the Environment, but also transaction values, container values and focused values
Related articles
Here are some more articles that may interest you. Check them out!
Matched Transitions in SwiftUI
published on September 23, 2025
SwiftSwiftUIAnimationsLearn how to use matchedGeometryEffect and navigationTransition in SwiftUI to create smooth, visually engaging transitions between views and screens. This article covers practical examples for synchronizing view geometry and implementing the new zoom navigation transition, helping you build more dynamic and polished UIs.
Read moreApp Enums and App Entities
published on September 20, 2025
SwiftAppIntentsAppEnum and AppEntity let you extend AppIntents in iOS with static and dynamic data, making your app’s features more accessible through Siri, Shortcuts, and Spotlight. This article explains how to use both for richer, more discoverable user experiences.
Read moreAppIntents
published on September 18, 2025
SwiftAppIntentsAppIntents in iOS make it easier to connect your app’s features with system-wide experiences like Siri, Shortcuts, and Spotlight. Instead of writing complex integrations, you can declare clear, type-safe intents that expose your app’s functionality to users in a natural way. This not only improves discoverability but also gives users faster, more personalized interactions with your app.
Read more