Revealed on: July 15, 2024
Including customized values to SwiftUI’s atmosphere has by no means been very exhausting to do to. Nonetheless, the syntax for doing it’s verbose and simple to neglect. To refresh your thoughts, check out this publish the place I clarify the best way to add your personal atmosphere 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 atmosphere utilizing Xcode 15 and earlier:
non-public 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 got to outline an atmosphere key, outline a default worth, and write a getter and setter to retrieve our worth from the atmosphere utilizing our key.
That is repetitive, simple to neglect, and simply annoying to do.
In the event you favor studying thorugh video, here is the video to look at:
Fortunately, in Xcode 16 now we have entry to the @Entry
macro. This macro permits us to outline the very same atmosphere 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 now we have to outline now could be a variable that’s annotated with @Entry
and we’re carried out.
The property title is used because the atmosphere key so on this case we’d set our date formatter like this:
myView
.atmosphere(.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 are able to use it in initiatives that focus on iOS variations older than 18! In order quickly as you begin growing your undertaking with Xcode 16 you’ll be capable to use this macro no matter your deployment goal.