Gosh Darn Format Style!
GitHub Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Creating Custom Format Styles

Visit the “Build a Format Style Workshop”.

As a protocol, FormatStyle is quite simple to conform to:

/// A type that can convert a given data type into a representation
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
public protocol FormatStyle : Decodable, Encodable, Hashable {

    /// The type of data to format.
    associatedtype FormatInput

    /// The type of the formatted data.
    associatedtype FormatOutput

    /// Creates a `FormatOutput` instance from `value`.
    func format(_ value: Self.FormatInput) -> Self.FormatOutput

    /// If the format allows selecting a locale, returns a copy of this format with the new locale set. Default implementation returns an unmodified self.
    func locale(_ locale: Locale) -> Self

Essentially, this provides you with the ability to convert any data type into any other data type or representation.

Here’s an example of a custom type (an ISBN) that supports FormatStyle, ParseableFormatStyle, and can output AttributedString values.

Read the blog post for more details

Download the Xcode Playground or See everything as a Gist

Defining Our ISBN

Creating Our FormatStyle

Adding AttributedString Output

Conforming to ParseableFormatStyle