Printed on: July 15, 2024
Including customized values to SwiftUI’s setting has by no means been very laborious to do to. Nonetheless, the syntax for doing it’s verbose and simple to overlook. To refresh your thoughts, check out this put up the place I clarify methods to add your personal setting values to a SwiftUI view.
To summarize what’s proven in that put up; right here’s the way you add a customized worth to the setting 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 got to outline an setting key, outline a default worth, and write a getter and setter to retrieve our price from the setting utilizing our key.
That is repetitive, straightforward 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 setting 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 could be a variable that’s annotated with @Entry
and we’re carried out.
The property identify is used because the setting key so on this case we’d set our date formatter like this:
myView
.setting(.dateFormatter, Dateformatter())
I completely love this new syntax as a result of it eliminates all of the boilerplate in a single go.
And one of the best a part of this macro?
We are able to use it in tasks that focus on iOS variations older than 18! In order quickly as you begin growing your undertaking with Xcode 16 you’ll be capable of use this macro no matter your deployment goal.