String的 toInt 和 integerValue 的区别

如题所述

在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 类似
温馨提示:答案为网友推荐,仅供参考
相似回答