簡體   English   中英

Swift-使用無法解析的標識符

[英]Swift - Use of unresolved identifier

我在同一函數中創建所有變量。 但是在函數的最后,即使它是在同一函數中創建的,我也無法達到該常數。

當我最后寫“ self.resultLabel.text = weather”時,Xcode向我顯示了一個錯誤的未解析標識符“ weather”的使用

我知道如何解決。 我需要在task方法啟動后立即啟動“天氣”並將其設置為“”,然后我應該在函數中更改其值,但是即使我不這樣做並且我在if閉包中創建它,也不應我可以在相同功能范圍內達到目標嗎?

我不明白為什么它會一直給我這個錯誤。

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()

您正在定義太多新的變量weather ,這些變量只能在它們所在的花括號之間局部可見。

定義weather的最佳位置是在task關閉的開始,並且必須刪除該變量隨后出現的所有varlet聲明。

這里是關鍵部分:

 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
    }

...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM