【问题标题】:Cannot subscript a value of type '[Any]' with an index of type 'String'无法使用“String”类型的索引为“[Any]”类型的值下标
【发布时间】:2019-08-30 01:38:21
【问题描述】:

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

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

我想将名称和价格存储到变量中,以便可以在表格视图中显示它们。如下面的代码所示,当我将 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)

                            }
                        }
                    }

【问题讨论】:

  • 你的对象snapshot 是什么类型的?那是字典还是对象数组?
  • [Any] 是一个Array<Any>。它不是一个可以用字符串下标的字典。

标签: swift dictionary


【解决方案1】:

如您所见,控制台输出中没有“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"] ?? ""
        //...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多