Connect with us

Articles

FormatStyle deep dive

Apple introduced the new FormatStyle protocol with iOS 15. It allows for some truly remarkable things to happen when you’re converting your data into localized strings.

Apple introduced the new FormatStyle protocol with iOS 15. It allows for some truly remarkable things to happen when you’re converting your data into localized strings.

In true Apple fashion though, details about how to use these new features are lightly documented with few examples.

The breadth and depth that this new functionality has been added to Swift is really nice, Apple has added support for it on nearly all data types in Swift. You also have the ability to create custom FormatStyle implementations that allow you to arbitrarily convert types using this functionality.

To use this functionality in the past, you would have needed to create a new instance of the various Formatter subclasses on offer (DateFormatterNumberFormatter, etc), configure it, and then use the instance to output our localized string. This came with the large gotcha that instantiating these formatters were expected, and you needed to know that you had to cache these somewhere in your app for quick reuse.

No more. According to Apple, the system is using these formatters under the hood and they’re now handling the creation and cacheing of these objects for you.

As an added bonus, Apple has added built-in support to the Text view in SwiftUI to fully support every FormatStyle detailed in this deep dive.

Download the Xcode Playground with all examples

See the examples as a gist

Full Article: Ampersand Softworks
Mar 12, 2022
Advertisement

Trending