I was thrown for a loop the other day when I tried to use
"\(someValue, specified: "%0.2f")" in a Playground. I had thought it was something new added to the language with a recent Xcode, but it turned out to be something in SwiftUI, and it only worked in very specific contexts even there (e.g.
It would be great to have those in the language generally. Imagine quick and easy formatting of a command-line tool, something that would've been done with
printf in the past.
Specifically, SwiftUI provides the following:
public mutating func appendInterpolation<Subject>(_ subject: Subject, formatter: Formatter? = nil) where Subject : ReferenceConvertible public mutating func appendInterpolation<Subject>(_ subject: Subject, formatter: Formatter? = nil) where Subject : NSObject public mutating func appendInterpolation<T>(_ value: T) where T : _FormatSpecifiable public mutating func appendInterpolation<T>(_ value: T, specifier: String) where T : _FormatSpecifiable
The first two would probably live as extensions in
Foundation, but the second two could be added to
DefaultStringInterpolation. I don't think it needs to be particularly fancy, it would be shorthand for
String(format:…), although there's some issue with localization and
There is some sentiment out there against format strings, but they're vastly convenient, and available in virtually every other language, and there are numerous posts online showing how to add formatting to string interpolation. Moreover, this proposal allows for using the more robust
I imagine this would be done in concert with Apple's SwiftUI team; no sense in them having their own version of this. And
_FormatSpecifiable would need to be formalized and made public.
(some time lurker, first time pitcher)