尝试更新将返回的do-catch块中的变量:致命错误:在解包可选值

时间:2016-11-08 19:22:56

标签: swift alamofire

我想返回来自currData类型的wData(自定义类型)。 currData在函数的开头声明,并将在do-catch块中设置:

func getWData(stnID: Int) -> wData{
   var currData: wData?

   let parameters: Parameters = ["id": String(stnID), "accesstype": "w"]

   Alamofire.request("https://myurl.tld", parameters: parameters).response { response in
       print("Request: \(response.request)")
       print("Response: \(response.response)")
       print("Error: \(response.data)")

       if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
           print("Data: \(utf8Text)")

           let dArr = utf8Text.components(separatedBy: "~")
           do {
               try currData = wData(hash: Int(dArr[0])!, stnName: String(dArr[1])!)
           } catch {
               print("error creating wData Object: \(error)")
           }

       }
   }   

   return currData!
}

但是当我尝试返回currData对象时,我收到以下错误消息:

  

致命错误:在解包可选值时意外发现nil

我的wData课程如下:

class wData{
     var hash: Int
     var stnName: String

     init(hash: Int, stnName: String) {
         self.hash     = hash
         self.stnName  = stnName
     }
}

我以为我可以在班上创建一个静态变量:

class wData{

     static var currDObj: wData?
     var hash: Int
     var stnName: String

     init(hash: Int, stnName: String) {
         self.hash     = hash
         self.stnName  = stnName

         currDObj = self
     }
}

然后使用以下命令返回我的getWData函数中的currDObj:

return weatherData.currData!

但它仍然给我一个错误。我做错了什么?

1 个答案:

答案 0 :(得分:1)

此行try currData = wData(hash: Int(dArr[0])!, stnName: String(dArr[1])!)很可能不会在此行return currData!之前进行评估,因此currData仍为零。您需要对函数使用闭包,而不是返回值。

这样的事情:(也提高了零安全性)

func getWData(stnID: Int, completion: (wData?) -> ()) {

    let parameters: Parameters = ["id": String(stnID), "accesstype": "w"]

    Alamofire.request("https://myurl.tld", parameters: parameters).response { response in
        print("Request: \(response.request)")
        print("Response: \(response.response)")
        print("Error: \(response.data)")

        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)")

            let dArr = utf8Text.components(separatedBy: "~")
            guard let hash = Int(dArr[0]), stnName = String(dArr[1]) else {
                completion(nil)
                return
            }
            do {
                let currData: wData = try wData(hash: hash, stnName: stnName)
                completion(currData)

            } catch {
                print("error creating wData Object: \(error)")
                completion(nil)
            }

        }
        else {
            completion(nil)
        }
    }
}