Search code examples
arraysswiftdowncast

SWIFT - Downcast an array to a string


@IBOutlet var cityField: UITextField!
@IBOutlet var message: UILabel!

@IBAction func buttonPressed(sender: AnyObject) {

   self.view.endEditing(true)       
   var urlString = "http://www.weather-forecast.com/locations/" + cityField.text.stringByReplacingOccurrencesOfString(" ", withString: "") + "/forecasts/latest"

    var url = NSURL(string: urlString)        
    let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, respons, error) in         
        var urlContent =  NSString(data: data, encoding: NSUTF8StringEncoding)            
        var contentArray = urlContent.componentsSeparatedByString("<span class=\"phrase\">")            
        var newContentArray = contentArray[1].componentsSeparatedByString("</span>")

        self.message.text = newContentArray[0] as? String            
        println(urlString)
    }        
    task.resume()        
}

Here is a simple weather app i'm making, my problem is when i click the button it doesn't really show the weather and it gives me this error "fatal error: Array index out of range" Help, please.


Solution

  • In this line:

        var newContentArray = contentArray[1].componentsSeparatedByString("</span>")
    

    You assume that contentArray will have at least two elements. If it doesn't, you will crash. Obviously that assumption is not correct. You cannot rely on data you receive from outside you app; you must validate that it's in the format you expect before processing it.