Including values to the SwiftUI setting with Xcode 16’s Entry macro – Donny Wals


Printed on: July 15, 2024

Including customized values to SwiftUI’s setting has by no means been very exhausting to do to. Nonetheless, the syntax for doing it’s verbose and straightforward to overlook. To refresh your thoughts, check out this submit the place I clarify find out how to add your personal setting values to a SwiftUI view.

To summarize what’s proven in that submit; right here’s the way you add a customized worth to the setting 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 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 now we have 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 now we have to outline now’s a variable that’s annotated with @Entry and we’re accomplished.

The property title 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 removes all of the boilerplate in a single go.

And the perfect a part of this macro?

We will use it in tasks that focus on iOS variations older than 18! In order quickly as you begin growing your venture with Xcode 16 you’ll be capable of use this macro no matter your deployment goal.

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox