String的 toInt 和 integerValue 的区别

 我来答
匿名用户
2017-05-15
展开全部
在Swift中,将String的字符串数字转换成整形数值可以使用toInt() 或者 integerValue,二者有一些细微的区别
1. integerValue 是 NSString 类的扩展。
[objc] view plain copy
@availability(iOS, introduced=2.0)
var integerValue: Int { get }

2. toInt() 是 String 结构体的扩展,用来求整数
[objc] view plain copy
/// If the string represents an integer that fits into an Int, returns
/// the corresponding integer. This accepts strings that match the regular
/// expression "[-+]?[0-9]+" only.
func toInt() -> Int?

区别:
1. 他们的返回值是不同的,toInt() 返回的是一个Option Value,所以在使用的时候要考虑到可能会是nil的情况,integerValue 返回的是一个确定的值,如果字符串是不能转换成Int的,那么会返回 0;

2. toInt() 是对整个字符串做一个转换,如果转换成功则返回Int值,否则返回nil;
[objc] view plain copy
"1".toInt() // result : 1
"1.1".toInt() // result : nil
"A".toInt() // result : nil
"1A".toInt() // result : nil

integerValue 是从第0位开始转换的,当遇到不能转换的时候停止转换并将之前转换的结果返回
[objc] view plain copy
"123".integerValue // result : 123
"123.456".integerValue // result : 123
"ABCDEFG".integerValue // result : 0
"123ABCDEFG".integerValue // result : 123
"ABCDEFG1234".integerValue // result : 0

: floatValue 和 integerValue 类似
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式