Fucking FormatStyle

I have a bit of a love-hate relationship with Swift’s FormatStyle-based formatting capabilities.

Text(progress.formatted(.percent.precision(.significantDigits(2))))

42%

(in English – results may vary depending on locale)

On the pro side:

  • They’re better than rolling your own formatting. Not just in terms of convenience, but in terms of correctness – they support localisation, for example. “42%” in English, “٤٢٪؜” in العربية (Arabic), “৪২%” in অসমীয়া (Assamese), “42 %” in Deutsch (German), etc.
  • They’re terser than using their otherwise more powerful cousins the Formatters, as they support a “fluent” style of property-based access, which tends to read more naturally and usually avoids having to define variables to hold the formatter.

But the cons are rough:

  • They almost always break Xcode’s auto-complete, which is a problem since their syntax is non-trivial and unintuitive.
  • They’re hard to understand – and to even find in Apple’s official documentation – because there’s so many protocols and indirection involved.

    It’s particularly hard to tell where the inexplicable gaps are. e.g. Double doesn’t support ByteCountFormatStyle, even though logically it should and Xcode will sometimes auto-complete as if it does. Worse, there’s often no valid compiler diagnostic if you try to use them together – you just get a long hang and eventually the dreaded “unable to type check in a reasonable time” cop-out.

All in all, there’s a reason fuckingformatstyle.com1 exists (and don’t forget to tip!).

  1. There’s also the alias goshdarnformatstyle.com if you want to pretend anybody doesn’t know exactly what you actually mean. I assure you that the stronger expletive is by far the most appropriate, once you have experience with FormatStyle. ↩︎

2 thoughts on “Fucking FormatStyle”

  1. I like that extensions exist to help smooth this down. I don’t like that these API ship to us like this to begin with.

    My ideal would be like:

    Text(progress.percent())

    Reply
    • Yeah, I end up with a family of asPercent convenience properties as well.

      I haven’t really cogitated on it, but I tend to feel that some simple methods would have been much easier (for humans and the compiler) than the existing, complex design. e.g. asPercent(…) with just all the relevant parameters as actual method parameters, all in one place, easy to auto-complete, hard to get lost in.

      That could also be added through extensions, I just haven’t happened to get that far yet – most of my uses are fairly specific, so I haven’t been compelled to generalise.

      Reply

Leave a Comment