'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<Any>
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?
Solution 1:[1]
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.
Solution 2:[2]
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
}
Solution 3:[3]
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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | rmaddy |
Solution 3 |