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协议自动解析,无需逐个字段取值:
- 让结构体遵守Codable协议:
struct RatingInfo: Codable { let currentRating: Double // 其他和Firestore文档字段对应的属性,名称要完全匹配 }
- 在监听回调中用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
相关产品推荐
相关产品推荐

