1

I am working with Swift's Decimal type, trying to ensure that an user-entered String is a valid Decimal.

I have two String values, each including a letter, within my Playground file. One of the values contains a letter at the start, while the other contains a letter at the end. I initialize a Decimal using each value, and only one Decimal initialization fails; the Decimal initialized with the value that contains the letter at the beginning.

Why does the Decimal initialized with a value that contains a letter at the end return a valid Decimal? I expect nil to be returned.

Attached is a screenshot from my Playground file.

Screenshot of code that produces a valid Decimal from a String with a trailing letter

Nick Kohrn
  • 5,779
  • 3
  • 29
  • 49

1 Answers1

2

It works this way because Decimal accepts any number values before the letters. The letters act as a terminator for any numbers that comes after it. So in your example:

12a = 12   ( a is the terminator in position 3 )
a12 = nil  ( a is the terminator in position 1 )

If wanting both to be invalid if the string contains a letter then you could use Float instead.

l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • 1
    The only exception really to note is when using scientific notation; the `e+` will not terminate the number, for example (`12.21e+03`) would be a valid string which would be rounded out to `12210`... – l'L'l Jun 03 '17 at 05:21