Revealed on: July 15, 2024
Including customized values to SwiftUI’s surroundings has by no means been very laborious to do to. Nevertheless, the syntax for doing it’s verbose and simple to overlook. To refresh your thoughts, check out this publish the place I clarify how you can add your personal surroundings values to a SwiftUI view.
To summarize what’s proven in that publish; right here’s the way you add a customized worth to the surroundings utilizing Xcode 15 and earlier:
personal struct DateFormatterKey: EnvironmentKey {
static let defaultValue: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MM/dd/yyyy"
return formatter
}()
}
extension EnvironmentValues {
var dateFormatter: DateFormatter {
get { self[DateFormatterKey.self] }
set { self[DateFormatterKey.self] = newValue }
}
}
We’ve to outline an surroundings key, outline a default worth, and write a getter and setter to retrieve our worth from the surroundings utilizing our key.
That is repetitive, simple to overlook, and simply annoying to do.
Fortunately, in Xcode 16 we’ve entry to the @Entry
macro. This macro permits us to outline the very same surroundings key like this:
extension EnvironmentValues {
@Entry var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MM/dd/yyyy"
return formatter
}()
}
All we’ve to outline now’s a variable that’s annotated with @Entry
and we’re achieved.
The property identify is used because the surroundings key so on this case we’d set our date formatter like this:
myView
.surroundings(.dateFormatter, Dateformatter())
I completely love this new syntax as a result of it removes all of the boilerplate in a single go.
And the perfect a part of this macro?
We will use it in initiatives that concentrate on iOS variations older than 18! In order quickly as you begin growing your venture with Xcode 16 you’ll have the ability to use this macro no matter your deployment goal.