Is it possible to create custom styles with the new Foundation formatters that were introduced in WWDC 2021? Currently, you could format numbers like this:
I want to create a new formatter that takes a number and converts to a formatted date component string. It would be great if this is already built in but I could not figure out the correct syntax if it exists. I would like to do something like this:
print(25.formatted(.number.dateComponent(style: .short, field: .minutes)))
// 25 min
For reference, this could be done the "old" way like this:
static let formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .short
formatter.allowedUnits = [.minute]
return formatter
}()
print(Self.formatter.string(for: DateComponents(minute: 25)))
// 25 min
Although, there's a lot of things I don't like about my implementation. What intrigued me most about the WWDC session is we no longer have to cache formatters statically which we were forced to do over the years to get around the heavy formatter instantiation. I was hoping this could be leveraged in the API. Maybe that's why FormatStyle needs to be Codable?, but nothing for certain about this.
I suppose you could store the formatter in a static variable to keep it alive, or even implement some kind of lookup table for different formatter configurations if that’s important for your use case.
(I never know if instantiating or (re-)configuring the formatter is the expensive operation, but I suspect it’s often the latter. If that’s true, just keeping the instance around may not help with performance if your formatted implementation regularly reconfigures it.)
The caching is all internal to the new formatting implementation at this time. Mostly because designing the huge API surface of all the styles themselves was enough of a challenge! Exposing the caches themselves so you can use it in a scenario like this is an interesting idea. I'll file a bug for you.