为什么从包含字母的字符串中快速返回十进制数? [英] Why is Swift Decimal Returning Number from String Containing Letters?
问题描述
我正在使用Swift的Decimal
类型,试图确保用户输入的String
是有效的Decimal
.
I am working with Swift's Decimal
type, trying to ensure that an user-entered String
is a valid Decimal
.
我的Playground文件中有两个String
值,每个值包含一个字母.其中一个值的开头是字母,另一个值的末尾是字母.我使用每个值初始化一个Decimal
,只有一个Decimal
初始化失败. 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.
为什么用结尾处包含字母的值初始化的Decimal
返回有效的Decimal
?我希望返回nil
.
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.
已附上我Playground文件中的屏幕截图.
Attached is a screenshot from my Playground file.
推荐答案
之所以这样工作,是因为Decimal
接受字母前的任何数字值.字母充当其后任何数字的终止符.因此,在您的示例中:
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 )
如果希望两者都无效(如果字符串中包含字母),则可以改用Float
.
If wanting both to be invalid if the string contains a letter then you could use Float
instead.
这篇关于为什么从包含字母的字符串中快速返回十进制数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!