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

Swift中通过读取函数将Firestore数据赋值给结构体变量

从Firestore文档中提取数据赋值给结构体变量

你不能直接用data.currentRating的原因是,document.data()返回的是[AnyHashable: Any]类型的字典,不是自定义对象,所以需要通过键取值或者用Codable协议来解析。下面是两种常用的实现方式:

方式一:直接从字典中取值并转换类型

假设你的结构体定义如下:

struct RatingInfo {
    var currentRating: Double
    // 可添加其他需要的属性
}

在监听回调中,通过字典的键提取对应值,并进行类型转换后赋值:

private func listenDocument() {
    Firestore.firestore().collection("RatingInformation").document("Brittain")
        .addSnapshotListener { documentSnapshot, error in
            guard let document = documentSnapshot else {
                print("Error fetching document: \(error!)")
                return
            }
            guard let data = document.data() else {
                print("Document data was empty.")
                return
            }
            
            // 提取currentRating并赋值给结构体
            if let currentRating = data["currentRating"] as? Double {
                var ratingInfo = RatingInfo(currentRating: currentRating)
                // 这里可以使用ratingInfo变量,比如更新UI等操作
                print("当前评分: \(ratingInfo.currentRating)")
            } else {
                print("currentRating字段缺失或类型不匹配")
            }
        }
}

注意:类型转换要和Firestore中存储的currentRating类型一致,如果存储的是整数就用as? Int,字符串就用as? String。

方式二:使用Codable协议解析(更优雅的批量处理)

如果你的结构体字段较多,推荐用Codable协议自动解析,无需逐个字段取值:

  1. 让结构体遵守Codable协议:
struct RatingInfo: Codable {
    let currentRating: Double
    // 其他和Firestore文档字段对应的属性,名称要完全匹配
}
  1. 在监听回调中用Firestore的内置方法解析:
private func listenDocument() {
    Firestore.firestore().collection("RatingInformation").document("Brittain")
        .addSnapshotListener { documentSnapshot, error in
            guard let document = documentSnapshot else {
                print("Error fetching document: \(error!)")
                return
            }
            
            do {
                // 直接将文档数据解析为结构体实例
                let ratingInfo = try document.data(as: RatingInfo.self)
                // 此时ratingInfo.currentRating已经赋值完成
                print("当前评分: \(ratingInfo.currentRating)")
                // 后续可使用ratingInfo进行业务操作
            } catch {
                print("解析数据失败: \(error)")
            }
        }
}

如果结构体属性名称和Firestore字段名称不一致,可以用CodingKeys枚举来映射对应关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:10:41