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!
The TimelineView
published on November 2, 2025
SwiftUILearn how to use SwiftUI’s TimelineView to build time‑based animations. This article explains scheduler options, shows practical examples (pauseable clock, smooth minute‑progress ring with hue shifts and tick marks), and helps you choose the right schedule for smooth or precise updates.
Read moreFoundation Models
published on October 8, 2025
SwiftAILearn how to use Apple’s foundation models to run large language models locally on iOS. This article covers chat, streaming responses, structured data generation, and custom tools, helping you build secure and responsive AI features without relying on the cloud.
Read moreWorking with CoreBluetooth
published on September 30, 2025
SwiftiOSDiscover how to use CoreBluetooth in iOS to build apps that communicate with Bluetooth Low Energy devices. This article explains the roles of central and peripheral, how services and characteristics work, and provides a practical example for implementing both sides of BLE communication in Swift.
Read more