You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore Swift:统计文档中嵌套Map的数量

统计Firestore嵌套Map的数量

当然可以统计嵌套Map的元素数量,只需将获取到的attendees转换为字典类型,再直接获取其键值对的数量即可。

修改你的代码如下:

db.collection("Collection")
    .document(eventID)
    .getDocument { doc, err in
        if let err = err {
            print(err.localizedDescription)
            return
        }
        guard let data = doc?.data(), 
              let attendees = data["attendees"] as? [String: Any] else {
            // 处理数据为空或类型转换失败的情况
            print("无法获取有效attendees数据")
            return
        }
        let attendeeCount = attendees.count
        print("参会者数量:\(attendeeCount)")
    }

关键说明:

  • Firestore中attendees对应字典(Map)结构,必须将data?["attendees"]强制转换为[String: Any]类型,才能调用字典的count属性获取元素数量。
  • 使用guard let做安全解包,避免空值或类型不匹配引发的崩溃。
  • attendees.count就是你需要的嵌套Map元素总数,对应示例中的2个。

内容的提问来源于stack exchange,提问作者Kelvin Jou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 01:33:24