Swift - Use of unresolved identifier

2019-09-17 20:50发布

问题:

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("&deg;", 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()

回答1:

You're defining too many new variables weather which are all visible only locally between the curly braces they are in.

The best place to define weather is at the beginning of the task closure and all var or let declarations of the subsequent occurrences of the variable have to be deleted.

Here the crucial part:

 let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in

    var weather = ""
    if let content = data {
      let urlContent = NSString(data: content, encoding: NSUTF8StringEncoding) as NSString!
      let weatherContent = urlContent.componentsSeparatedByString("<span class=\"phrase\">")
      if weatherContent.count > 1 {
        weather = weatherContent[1].componentsSeparatedByString("</span>")[0].stringByReplacingOccurrencesOfString("&deg;", withString: "˚")
      } else {
        errorStatus = true
      }
    } else {
      errorStatus = true
    }

...