【问题标题】:Loop through object fields in firestore with Swift使用 Swift 遍历 firestore 中的对象字段
【发布时间】:2018-01-01 17:14:21
【问题描述】:

我有一份文件。它在“产品”中有一堆对象字段 如何循环浏览这本字典?

let dict = doc.data()

for (key,value) in dict["products"]{

}

这给了我错误:

输入“任何?”不符合协议'Sequence'

我的明显问题是什么?

编辑:文档说

/**
* Retrieves all fields in the document as an `NSDictionary`.
*
* @return An `NSDictionary` containing all fields in the document.
*/
- (NSDictionary<NSString *, id> *)data;

【问题讨论】:

  • 你能和我们分享一下doc.data()实际上返回了什么吗?

标签: swift google-cloud-firestore


【解决方案1】:

你应该使用:

let dict = doc.data()

if let products = dict["products"] as? [AnyHashable: Any] {

    for (key,value) in products {

    }
}

doc.data() 返回Any?,因此要将其视为Dictionary,您需要将其转换为Dictionary

【讨论】:

  • 字典中的键不必一直是String 类型。你应该检查Hashable 而不是as? [Hashable: Any]
  • 错误是什么?我更新了代码,所以我们现在遍历返回的字典的元素,它可能包含另一个字典作为“产品”键的值。
  • 错误:不支持使用 'Hashable' 作为符合协议 'Hashable' 的具体类型
  • 如果您确定返回的字典键是String 类型,则将Hashable 替换为String
  • @jimijon 如果您不确定,请查看我更新的答案。
猜你喜欢
  • 1970-01-01
  • 2023-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
相关资源
最近更新 更多