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 RawRepresentable protocol
published on February 15, 2025
SwiftIf you’ve ever used a Swift enum with a raw value, you may not even realise that you have already worked with the RawRepresentable protocol. But what is it and how can you make use of it? In this article we are going to investigate the RawRepresentable protocol and I’m going to show you some neat ways for using the protocol to our advantage.
Read moreProportional layout with SwiftUI
published on January 25, 2025
SwiftUISwiftStarting from iOS 16, SwiftUI gives us the option to build custom layouts that can control very precisely where each subview should be placed. We have the option to build layouts that can be used just as the VStack, HStack or any other built in Layout you may be familiar with from SwiftUI.
Read moreThe @ and # symbols in Swift
published on January 2, 2025
SwiftWhen a new feature is introduced in a programming language, we as developers are often quick to assume it will solve many of their challenges. The excitement to experiment with such features is natural, but it’s often accompanied by the realisation that every solution brings its own set of unique challenges. This was no different when actors were introduced.
Read more