In a program I'm making, Im trying to access web content to display the weather. I'm struggling with the concept of optionals and I'm wondering why this line of code works when a "?" is added, but not without.
@IBAction func pressedSearch(sender: AnyObject) {
var urlString = "http://www.weather-forecast.com/locations/" + cityField.text.stringByReplacingOccurrencesOfString(" ", withString: "") + "/forecasts/latest"
var url = NSURL(string: urlString)
println(urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)
var contentArray = urlContent?.componentsSeparatedByString("<span class=\"phrase\">") as Array<String>
println(contentArray[1])
}
task.resume()
}
Here is the line of code where the "?" was added to make the code work:
var contentArray = urlContent?.componentsSeparatedByString("<span class=\"phrase\">") as Array<String>
What does the "?" do to fix the error, and why do we have to add "?" and "!" to some variables and not others throughout swift?