为什么从包含字母的字符串中快速返回十进制数? [英] Why is Swift Decimal Returning Number from String Containing Letters?

查看:134
本文介绍了为什么从包含字母的字符串中快速返回十进制数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆