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