使用Codable类读取Firestore全集合时的@DocumentID报错问题
解决Firestore @DocumentID手动赋值警告问题
问题根源
警告的核心原因是:@DocumentID 属性是Firestore用来绑定文档ID的专属字段,它的值应该由Firestore自动读取/生成,而非手动赋值。当你手动给这个属性设置非空值时,Firestore会直接忽略该值,同时抛出警告提示。
具体解决方案
1. 修正Evento类的@DocumentID属性定义
将@DocumentID标记的字段设为可选类型,避免初始化时必须手动赋值:
import FirebaseFirestoreSwift struct Evento: Codable { @DocumentID var id: String? // 设为可选,无需手动赋值 var nombre: String var fecha: Date // 其他业务属性... }
2. 读取全集合时,让Firestore自动填充ID
在cargarEventos函数中,直接通过Firestore的data(as:)方法解码,不要手动给id字段传值:
func cargarEventos() async throws -> [Evento] { let db = Firestore.firestore() let snapshot = try await db.collection("eventos").getDocuments() return snapshot.documents.compactMap { document in try? document.data(as: Evento.self) // Firestore自动将文档ID填入id字段 } }
3. 写入数据时,通过Firestore API指定ID(如需)
如果需要自定义文档ID,不要手动设置Evento的id属性,而是通过Firestore的document(_:)方法指定:
func guardarEvento(evento: Evento) async throws { let db = Firestore.firestore() // 自定义ID或用UUID生成,通过document方法传入 let targetDocRef = db.collection("eventos").document(evento.id ?? UUID().uuidString) try targetDocRef.setData(from: evento) }
关键注意点
- 永远不要手动给
@DocumentID标记的字段赋值,无论是读取还是写入场景。 - 读取时,Firestore会自动把当前文档的ID填充到该字段;写入时,若需自定义ID,通过文档引用的方式指定,而非修改Codable对象的
@DocumentID字段。
内容的提问来源于stack exchange,提问作者Monrac
相关产品推荐
相关产品推荐

