gpt4 book ai didi

swift - 无法使用 '[Any]' 类型的索引为 'String' 类型的值添加下标

转载 作者:行者123 更新时间:2023-11-30 10:37:11 24 4
gpt4 key购买 nike

我正在从 firestore 检索数据,到目前为止一切都很成功。这是我的控制台中的结果。

[{
Name = Tuna;
Price = "$3.6"; }, {
Name = Snapper;
Price = "$25.60"; }]

我想将名称和价格存储到变量中,以便可以在 TableView 中显示它们。如下面的代码所示,当我将 nameOfItem 设置为 Data2 时,我收到一条错误,指出“无法使用“String”类型的索引为“[Any]”类型的值添加下标”。我想知道是否有人可以帮我解决这个问题!

 override func viewWillAppear(_ animated: Bool) {
itemCollectionRef.getDocuments { (snapshot, error) in
if let err = error {
debugPrint("Error fetching docs: \(err)")

}else {
guard let snap = snapshot else {return}
for document in snap.documents {
let data2 = document.data()["Items"]! as? Array ?? []
print(data2)
let RandomVariable = data2[0]
print(RandomVariable)

let nameOfItem = data2["Name"] as? String ?? ""
let priceOfItem = data2["Price"] as? String ?? ""

//let priceOfItem = data2["Price"] as? String ?? ""
//print(nameOfItem, priceOfItem)

}
}
}

最佳答案

正如您自己所看到的,控制台输出中没有“Items”元素之类的东西,而是因为错误消息表明您有一个数组,因此将 for 循环内的代码更改为

let data = document.data() as? [Any] ?? []
for item in data {
if let dictionary = item as? [String: String] {
let nameOfItem = dictionary["Name"] ?? ""
let priceOfItem = dictionary["Price"] ?? ""
//...
}
}

关于swift - 无法使用 '[Any]' 类型的索引为 'String' 类型的值添加下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57719489/

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