简体   繁体   中英

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.

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'".

How do I convert this "Any" to Int so I can add them?

Thanks in advanced.

Use optional binding to ensure the values are non-nil strings and that they can be converted to 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:

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 . 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) . Leading and trailing spaces are ignored and a floating point value such as 13.1 will be converted to an integer. 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
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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