-1

I found odd behavior in the Swift standard library struct Double(). This function converts a string representing a number into a double precision number. All well and good.

I recently discovered odd behavior wrt to leading whitespace, namely the conversion fails if a single blank character space leads a valid number string:

Example (Xcode Debugger)

(lldb) po Double("11.8000")
▿ Optional<Double>
  - some : 11.8

(lldb) po Double(" 11.8000")
nil

I have not seen this documented, so I post it here. The inelegant fix is:

let myNumber = Double(myString.trimmingCharacters(in: .whitespaces))

Any better solution? I mean aside from a simple String Extension to replace trimmingCharacters(in: .whitespaces) with trim(). I would think Double() and its relatives should be able to internally handle leading and trailing spaces.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
BlueskyMed
  • 765
  • 7
  • 24

1 Answers1

3

This is fully documented. Look at the documentation for the init method that takes a StringProtocol.

Near the end of all of the examples, it states:

Passing any other format or any additional characters as text results in nil. For example, the following conversions result in nil:

Double(" 5.0")      // Includes whitespace

So your solution to trim whitespace before conversion is the correct one.

Community
  • 1
  • 1
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks rmaddy, I looked at the standard library entry for Double, and googled around the web as well. I failed to look at the init method. My bad. – BlueskyMed Jul 15 '19 at 15:47
  • Not to belabor the point about trimmed strings, it does seem reasonable to me (at least), that trimming could be internal. External blanks are a far cry from random punctuation and alpha characters in the midst of numeric chars. Just looks hacky. But again, thanks for the response. – BlueskyMed Jul 15 '19 at 16:11