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 reentrancy problem
When 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 moreTips and tricks for iOS & macOS cross platform development
You may have heard how incredibly easy it is to develop user interfaces that work well in all platforms with SwiftUI. But I have some bad news for you, while SwiftUI indeed makes our lives a lot easier, you will still have to invest some time to get the best results out of it.
Read moreDebugging memory leaks in Xcode
Ever got into a situation where you observed some strange behaviour with your app? Crashes, very bad performance or strange warnings in the console? Or simply you looked at the memory usage of your app and realised that it’s way too high for what your app should be doing? Yeah! Most likely you are dealing with a memory leak.
Read more