I create all the variables within the same function. But at the end of the function I can't reach the constant even though it was created in the same function.
When I write "self.resultLabel.text = weather" at the end, Xcode shows me an error use of unresolved identifier 'weather'
I know how to fix it. I need to initiate 'weather' just after the task method starts and set it to "" and then I should change its value in the function but even if I don't do it and I create it in the if closures, shouldn't I be able to reach it while within the same function?
I don't understand why it keeps me giving this error.
func findWeather() {
var errorStatus = false
city = (cityField.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))!
let url = NSURL(string: "http://www.weather-forecast.com/locations/" + city.stringByReplacingOccurrencesOfString(" ", withString: "-") + "/forecasts/latest")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
if let content = data {
let urlContent = NSString(data: content, encoding: NSUTF8StringEncoding) as NSString!
let weatherContent = urlContent.componentsSeparatedByString("<span class=\"phrase\">")
if weatherContent.count > 1 {
let weather = weatherContent[1].componentsSeparatedByString("</span>")[0].stringByReplacingOccurrencesOfString("°", withString: "˚")
} else {
var weather = ""
errorStatus = true
}
} else {
var weather = ""
errorStatus = true
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if errorStatus == true {
self.showError()
} else {
self.resultLabel.text = weather // I get error: use of unresolved identifier 'weather'
}
})
}
task?.resume()