为什么Firestore可编码支持不适用于此示例



在第一个示例中,它编译并正确返回所有Project文档。

public struct Project: Codable, Identifiable, Equatable {

@DocumentID public var id : String? = UUID().uuidString
public var name: String
public var password: String
}
public static func testQuery() async ->  [Project] {
let db = Firestore.firestore()
let ref = db.collection("Project")
let snapshot = try? await ref.getDocuments()
if let snapshot = snapshot {
return snapshot.documents.compactMap { document in
return try? document.data(as: Project.self)
}
} else {
return [Project]()
}
}

但是,如果我将ref更改为声明为Query,文档将不再支持codable。如何修复此问题,因为我需要使用Query根据传递的参数动态构建查询。

public static func testQuery() async ->  [Project] {
let db = Firestore.firestore()
let ref: Query = db.collection("Project")  // this line changed
let snapshot = try? await ref.getDocuments()
if let snapshot = snapshot {
return snapshot.documents.compactMap { document in
return try? document.data(as: Project.self). // this no longer compiles
}
} else {
return [Project]()
}
}

事实证明,如果将ref从Query转换为CollectionReference,则可以使用内置的编码和解码功能。

public static func testQuery() async ->  [Project] {
let db = Firestore.firestore()
let ref: Query = db.collection("Project")  // this line changed
let ref2 = ref as! CollectionReference
let snapshot = try? await ref2.getDocuments()
if let snapshot = snapshot {
return snapshot.documents.compactMap { document in
return try? document.data(as: Project.self). // this no longer compiles
}
} else {
return [Project]()
}
}

最新更新