I'm trying to use FormatStyle
from Foundation
to format numbers when printing a vector structure. See code below.
import Foundation
struct Vector<T> {
var values: [T]
subscript(item: Int) -> T {
get { values[item] }
set { values[item] = newValue }
}
}
extension Vector: CustomStringConvertible {
var description: String {
var desc = "( "
desc += values.map { "\($0)" }.joined(separator: " ")
desc += " )"
return desc
}
}
extension Vector {
func formatted<F: FormatStyle>(_ style: F) -> String where F.FormatInput == T, F.FormatOutput == String {
var desc = "( "
desc += values.map { style.format($0) }.joined(separator: " ")
desc += " )"
return desc
}
}
In the example below, the vector contains a mix of integer and float literals. The result is a vector with a type of Vector<Double>
. Since the values of the vector are inferred as Double
then I expect the print output to display as decimal numbers. However, the .number
formatted output seems to ignore the vector type and print the values as a mix of integers and decimals. This is fixed by explicitly providing a format style with a fraction length. So why is the .formatted(.number)
method ignoring the vector type T
which is Double
in this example?
let vec = Vector(values: [-2, 5.5, 100, 19, 4, 8.37])
print(vec)
print(vec.formatted(.number))
print(vec.formatted(.number.precision(.fractionLength(1...))))
( -2.0 5.5 100.0 19.0 4.0 8.37 ) // correct output that uses all Double types
( -2 5.5 100 19 4 8.37 ) // wrong output that uses Int and Double types
( -2.0 5.5 100.0 19.0 4.0 8.37 ) // correct output that uses all Double types
I'm always conflicted on where to ask questions: on here or on the swift forum.
Yeah, it’s tricky. My general advice is to use Swift Forums if your question only involves open source stuff. If you could, in principle, reproduce the problem on Linux, that’s for Swift Forums. OTOH, if the problem relies on Xcode or any Apple APIs, that’s for DevForums.
However, it’s not always so clear cut. For example, in your case the FormatStyle
stuff was Apple specific until very recently.
ps It’s better to reply as a reply, rather than in the comments; see Quinn’s Top Ten DevForums Tips for this and other titbits.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"