gpt4 book ai didi

swift - 转换为 Swift 4,不明确的下标错误

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

我是 swift 的新手,目前在突出显示的代码部分面临问题,错误是下标的使用不明确。我尝试了在 stackoverflow 上可以找到的其他解决方案,但无法解决。请帮助我了解错误及其解决方案。

do{
guard let jsonData = data else {
throw MyError.FoundNil("JSON data issue!")
}

guard let dictionaryData = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [String:AnyObject] else {
throw MyError.SerializationError("Unable to serialize")
}

guard let city = dictionaryData["city"]!["name"]!,
// Error on next three lines
let data1 = dictionaryData["list"]![0]! as? [String: AnyObject],
let data2 = dictionaryData["list"]![1]! as? [String: AnyObject],
let data3 = dictionaryData["list"]![2]! as? [String: AnyObject],
let t1 = data1["t"] as? [String: AnyObject],
let t2 = data2["t"] as? [String: AnyObject],
let t3 = data3["t"] as? [String: AnyObject],
let wDay1 = data1["w"]![0]! as? [String:AnyObject],
let wDay2 = data2["w"]![0]! as? [String:AnyObject],
let wDay3 = data3["w"]![0]! as? [String:AnyObject]
else {
throw MyError.DataPopulateError("Mismatch in assigning values from dictionary")
}

最佳答案

首先,不要使用AnyObject。将您的字典定义为 [String: Any]

接下来,问题是一旦您执行了类似dictionaryData["some key"] 的操作,您现在就有了一个Any。需要进行转换才能进一步处理它。错误是由于尝试在 Any 上使用数组索引访问。

最后,您误用了 ! 运算符。 guard let 的全部意义在于安全地解包和安全地转换一个值。您使用 ! 打败了整点,如果数据不是您的代码假定的数据,这将使您的应用程序崩溃。

将第 2 个守卫更新为:

guard let dictionaryData = try? JSONSerialization.jsonObject(with: jsonData, options: []) as! [String:Any] else {
throw MyError.SerializationError("Unable to serialize")
}

然后重写你的大guard如下:

guard let city = (dictionaryData["city"] as? [String:Any])?["name"] as? String,
let list = dictionaryData["list"] as? [[String:Any]], list.count >= 3,
let t1 = list[0]["t"] as? [String:Any],
let t2 = list[1]["t"] as? [String:Any],
let t3 = list[2]["t"] as? [String:Any],
let wDay1 = (list[0]["w"] as? [[String:Any]])?.first,
let wDay2 = (list[1]["w"] as? [[String:Any]])?.first,
let wDay3 = (list[2]["w"] as? [[String:Any]])?.first
else {
throw MyError.DataPopulateError("Mismatch in assigning values from dictionary")
}

关于swift - 转换为 Swift 4,不明确的下标错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50555691/

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