Reputation: 99
I am accessing an API for weather and when I parse the JSON the result is a string. Since, the value I am accessing is a number, I want to convert it to an integer, but when the string has a decimal value, the string does not convert to an int. My code:
let UVIndex = swiftyJSON["current_observation"]["UV"].stringValue
let cityName = swiftyJSON["current_observation"]["display_location"]["full"].stringValue
if let UVIndexInt = Int(UVIndex) {
print("Successfully converted! \(UVIndexInt)")
self.UVIndexString = String(stringInterpolationSegment: UVIndex)
}
dispatch_async(dispatch_get_main_queue()) {
self.UVIndexButton.setTitle(self.UVIndexString, forState: UIControlState.Normal)
self.cityName.text = cityName
}
Upvotes: 1
Views: 330
Reputation: 73206
Another alternative; in essence same technique as in appzYourLife answer, but using a closure:
let toInt : (String) -> (Int?) = { Double($0) == nil ? nil : Int(Double($0)!) }
var text = "1.1"
toInt(text) // 1
text = "notANumber"
toInt(text) // nil
Note that both this and the accepted solution will yield a runtime exception if, for some reason, text
contains a number literal (in a string, naturally) which is larger than Int.max
(on my 64 bit system: 9223372036854775807
). Possibly not likely, but if you want to take extra care (some crazy UV index?) you should take measures against this (e.g. truncating).
Upvotes: 1
Reputation: 59536
You can try to convert the String
to Double
and then to Int
.
let text = "1.1"
if let textAsDouble = Double(text) {
let textAsInt = Int(textAsDouble)
print(textAsInt)
}
Upvotes: 5
Reputation: 42479
An alternate solution without converting the the input string to a Double
and then an Int
would be to use an NSNumberFormatter
to create an NSNumber
from your string. This way, you can get an Int
or the fixed-width Int32
type from your string:
let val = "1.1"
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.numberFromString(val)?.intValue // Int32
formatter.numberFromString(val)?.integerValue // Int
Upvotes: 4