[iOS/Swift]String的 toInt() 和 integerValue 的区别

在Swift中,将String的字符串数字转换成整形数值可以使用toInt() 或者 integerValue,二者有一些细微的区别

1. integerValue 是 NSString 类的扩展。

@availability(iOS, introduced=2.0)
    var integerValue: Int { get }

2. toInt() 是 String 结构体的扩展,用来求整数

/// 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;

"1".toInt()     // result : 1
"1.1".toInt()   // result : nil
"A".toInt()     // result : nil
"1A".toInt()    // result : nil

integerValue 是从第0位开始转换的,当遇到不能转换的时候停止转换并将之前转换的结果返回

"123".integerValue          // result : 123
"123.456".integerValue      // result : 123
"ABCDEFG".integerValue      // result : 0
"123ABCDEFG".integerValue   // result : 123
"ABCDEFG1234".integerValue  // result : 0

: floatValue 和 integerValue 类似

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值