如何在Swift 5中将文档转换为自定义对象? [英] How to convert document to a custom object in Swift 5?
问题描述
我一直试图将从Firebase的Cloud Firestore检索到的文档转换为Swift 5中的自定义对象.我正在关注文档:
I've been trying to convert the document retrieved from the Firebase's Cloud Firestore to a custom object in Swift 5. I'm following the documentation:
但是,Xcode向我显示行try $0.data(as: JStoreUser.self)
的错误Value of type 'NSObject' has no member 'data'
.我已将结构定义为Codable
.
However, Xcode shows me the error Value of type 'NSObject' has no member 'data'
for the line try $0.data(as: JStoreUser.self)
. I've defined the struct as Codable
.
代码:
func getJStoreUserFromDB() {
db = Firestore.firestore()
let user = Auth.auth().currentUser
db.collection("users").document((user?.email)!).getDocument() {
(document, error) in
let result = Result {
try document.flatMap {
try $0.data(as: JStoreUser.self)
}
}
}
}
用户结构:
public struct JStoreUser: Codable {
let fullName: String
let whatsApp: Bool
let phoneNumber: String
let email: String
let creationDate: Date?
}
屏幕截图:
有人知道如何解决这个问题吗?
Does anyone know how to resolve this?
推荐答案
与Firebase团队联系后,我找到了所需的解决方案.事实证明,我必须显式地执行import FirebaseFirestoreSwift
而不是仅仅执行import Firebase
.此后错误将消失. (当然,您首先需要将Pod添加到您的Podfile中:D)
After contacting the firebase team, I found the solution I was looking for. It turns out I have to do import FirebaseFirestoreSwift
explicitly instead of just doing import Firebase
. The error will disappear after this. (And of course you'll need to add the pod to your podfile first:D)
这篇关于如何在Swift 5中将文档转换为自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!