1

I'm taking data from an api and storing it in a string variable. When I print the variable it returns what I'm looking for but when I try to convert it to an int using the .toInt method it returns a nil?

func getWeather() {
    let url = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml")

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
        (data, response, error) in
        if error == nil {
            var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!
            var urlContentArray = urlContent.componentsSeparatedByString("temperature value=\"")
            var temperatureString = (urlContentArray[1].substringWithRange(NSRange(location: 0, length:6))) as String
            println(temperatureString) // returns 272.32
            var final = temperatureString.toInt()
            println(final) //returns nil
            println(temperatureString.toInt())
            self.temperature.text = "\(temperatureString)"
        }
    }
    task.resume()
}
Stefan Arentz
  • 33,205
  • 8
  • 66
  • 86
Nikola Jankovic
  • 909
  • 11
  • 23

3 Answers3

4

Even simpler, though slightly a trick, you can use integerValue:

temperatureString.integerValue

Unlike toInt, integerValue will stop converting when it finds a non-digit (it also throws away leading spaces.

If temperatureString is a String (rather than an NSString), you'll need to push it over:

(temperatureString as NSString).integerValue
Rob Napier
  • 266,633
  • 34
  • 431
  • 565
1

That's because 272.32 is not an integer.

You could convert it to a Float.

Community
  • 1
  • 1
Thilo
  • 250,062
  • 96
  • 490
  • 643
0

272.32 isn't an Integer. If your temperature string is an NSString, you can do this to convert it:

Int("272.32".floatValue)
kellanburket
  • 11,202
  • 3
  • 41
  • 68