gpt4 book ai didi

swift - 尝试更新将返回 : fatal error: unexpectedly found nil while unwrapping an Optional value 的 do-catch block 中的变量

转载 作者:行者123 更新时间:2023-11-28 06:30:28 25 4
gpt4 key购买 nike

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

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 对象时,我收到以下错误消息:

fatal error: unexpectedly found nil while unwrapping an Optional value

我的 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 仍然是 nil。您需要在函数中使用闭包而不是返回值。

像这样的东西:(也提高了 nil 的安全性)

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 - 尝试更新将返回 : fatal error: unexpectedly found nil while unwrapping an Optional value 的 do-catch block 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40494856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com