SwiftGen icon indicating copy to clipboard operation
SwiftGen copied to clipboard

Strings: Floating point placeholders use `Float` instead of `Double`

Open mluisbrown opened this issue 3 years ago • 2 comments

All the floating point placeholders (a, e, f, and g) translate to the Float type:

https://github.com/SwiftGen/SwiftGen/blob/f79fa84e7088cdcadf43c69cd1f4e96d996ce171/Sources/SwiftGenKit/Parsers/Strings/PlaceholderType.swift#L25-L26

However this Tech Doc from Apple indicates that they should be treated as Double

image

In Swift, Float is a 32 bit floating point number, and Double is a 64-bit floating point number

I'm creating this as an Issue rather than a PR in case there is something I have missed about why Float was chosen instead of Double

mluisbrown avatar Dec 11 '20 11:12 mluisbrown

Not sure TBH.

Docs / Technical

I've tried a quick search in some apple docs, and for Swift there's no real mention of the data type, whenever floating point is mentioned in relation to Strings (for other APIs), they use Float and Double interchangeably.

Do note that the tech. docs you linked are part of the (very) old Apple docs, not updated since 2014 (before Swift was released, and I think only just after the switch to arm64). And always be careful about switching between types that specify the number of bits explicitly, and those that don't:

  • Float32 and Float64 explicitly mention the number of bits
  • Float and Double do not, and that's not accidental: the number of bits of Float/Double depend on the architecture you run it on. Actually, the same applies to double (in Obj-C).

Double is "usually" is 64 bits, but that's because what it maps to on most (all?) architectures we run code on nowadays.

So if we really want to be correct, we'd maybe have to use Float64? Or would their mention of double (obj-c) infer that, if we ever switch to 128-bit, that format specifier will accept 128 bits?

Consequences

Besides that mostly pedantic bit above, I don't see any reasons why we couldn't (eventually) switch to Double. Note that "eventually". This would be a breaking change for some people, as their code wouldn't compile anymore: they'd need to add casts to Double where before the generated code accepted Floats.

The result though, of passing raw Floats or Doubles to string(format:) will be (almost) the same: mostly junk. The only scenario where passing such raw values would be visible, is if the developer doesn't specify a maximum number of fractional digits, so %f for example. And that is something the user probably doesn't want to see.

Note: should people even be using floats in strings like that? No, absolutely not, they should be using NumberFormatter, but that's unrelated to the issue here.

djbe avatar Dec 14 '20 16:12 djbe