我想返回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!

但它还是给了我一个错误。我做错了什么?

最佳答案

这一行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)
        }
    }
}

关于swift - 尝试更新将返回的do-catch块中的变量:致命错误:在展开可选值时意外发现nil,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40494856/

10-10 20:58