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
  • 34,311
  • 8
  • 67
  • 88
Nikola Jankovic
  • 947
  • 1
  • 13
  • 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
  • 286,113
  • 34
  • 456
  • 610
1

That's because 272.32 is not an integer.

You could convert it to a Float.

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656
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
  • 12,250
  • 3
  • 46
  • 73