Why is this acceptable:
Text("$\(item.price, specifier: "%.2f")")
but this isn’t:
let formattedPrice = "$\(item.price, specifier: "%.2f")"
The error I get is “Extra argument ‘specifier’ in call”
Isn’t specifier an argument to the String interpolation, rather than to the Text function?
It’s because Text
in your first example is interpreted by the compiler as using this initializer:
init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil)
LocalizedStringKey
has as part of its conformance to ExpressibleByStringLiteral
this method:
mutating func appendInterpolation<T>(_ value: T, specifier: String) where T : _FormatSpecifiable
Note the specifier
parameter.
If you look at the docs for String
, however, you’ll see that it has no such version of appendInterpolation
so you cannot use a specifier
parameter with just a string.
You can either extend String.StringInerpolation
with an appropriate appendInterpolation
method or you can format the string yourself. Something like this would work:
let formattedPrice = String(format: "%.2f", item.price)
Text
LocalizedStringKey.StringInterpolation
String.DefaultStringInterpolation
Thank you. Your second, much simpler, suggestion worked perfectly.