Why is Swift Decimal Returning Number from String Containing Letters?

人盡茶涼 提交于 2020-01-07 03:15:31

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/44339789/why-is-swift-decimal-returning-number-from-string-containing-letters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!