简体   繁体   English

如何将NSString转换为Int,以便我可以添加Swift 3.0

[英]How to convert NSString to Int so I can add in swift 3.0

I have a value which seems to be an Int but when I do type(of: value) it returns Optional and after trying many things I figure that data type NSString. 我有一个似乎是Int的值,但是当我输入type(of:value)时,它返回Optional,在尝试了许多事情之后,我发现数据类型为NSString。

let sum = data[0]["total1"] + data[0]["total2"]

I have two values like that and I want to add them but it does not let me do it with saying "binary operator + cannot be applied to two "Any" operands" or "Value of type "Any" has no member 'intValue'". 我有两个这样的值,但我想将它们相加,但是它不允许我说“二进制运算符+无法应用于两个“任何”操作数”或“类型为“任何”的值没有成员'intValue' ”。

How do I convert this "Any" to Int so I can add them? 如何将“任何”转换为Int,以便可以添加它们?

Thanks in advanced. 提前致谢。

Use optional binding to ensure the values are non-nil strings and that they can be converted to Int . 使用可选绑定确保值是非nil字符串,并且可以将它们转换为Int

if let str1 = data[0]["total1"] as? String, let str2 = data[0]["total2"] as? String {
    if let int1 = Int(str1), let int2 = Int(str2) {
        let sum = int1 + int2
    } else {
        // One or more of the two strings doesn't represent an integer
    }
} else {
    // One or more of the two values is nil or not a String
}

Since the underlying objects are NSString , you can also do: 由于基础对象是NSString ,因此您还可以执行以下操作:

if let num1 = (data[0]["total1"] as? NSString)?.intValue,
   let num2 = (data[0]["total2"] as? NSString)?.intValue {
    let sum = num1 + num2
}

As @rmaddy pointed out in the comments, if a value is not an integer (such as "hello" ), it will convert to 0 . 正如@rmaddy在评论中指出的那样,如果值不是整数(例如"hello" ),它将转换为0 Depending on your knowledge of the data your app is receiving and what you want to happen in this case, that result may or may not be appropriate. 根据您对应用程序正在接收的数据的了解以及在这种情况下要发生的情况,该结果可能合适也可能不合适。

.intValue is more forgiving of the string data format compared to Int(str) . Int(str)相比, .intValue更能容忍字符串数据格式。 Leading and trailing spaces are ignored and a floating point value such as 13.1 will be converted to an integer. 前导空格和尾随空格将被忽略,浮点值(如13.1将转换为整数。 Again, it depends on what you want to happen in your app. 同样,这取决于您想要在应用程序中发生什么。

This is how I do it: 这是我的方法:

extension String {
    var asInt: Int? {
        return Int(self)
    }
    var isInt: Bool {
        return Int(self) != nil
    }
}

call it as follows (assuming a property called result):

        let stringOne = "14"
        let stringTwo = "12"
        if  stringOne.isInt && stringTwo.isInt {
            self.result = stringOne.asInt + stringTwo.asInt
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM