如何初始化 Firestore 文档参考 Swift
How to Initialize Firestore Document Reference Swift
我有一个如下所示的用户模型,它给了我一个 User
.
的字典
import UIKit
import FirebaseFirestore
protocol SerializeUser {
init?(dictionary: [String: Any])
}
struct User {
var documentRef: DocumentReference?
var displayName: String
var photoURL: String
var email: String
var isEmployee: Bool
var dictionary: [String: Any] {
return ["displayName": displayName, "photoURL": photoURL, "email": email, "isEmployee": isEmployee]
}
}
extension User: SerializeUser {
init?(dictionary: [String: Any]) {
guard
let displayName = dictionary["displayName"] as? String,
let photoURL = dictionary["photoURL"] as? String,
let isEmployee = dictionary["isEmployee"] as? Bool,
let email = dictionary["email"] as? String else { return nil }
self.init(displayName: displayName, photoURL: photoURL, email: email, isEmployee: isEmployee)
}
}
我需要以某种方式在我的 User
结构中初始化 documentRef
关于如何做到这一点的任何想法?请
在某处您需要数据库实例来构建文档引用。
var db: Firestore? = Firestore.firestore()
struct User {
lazy var documentRef: db.collection("users").document(displayName)
}
我在这里的任何地方都没有看到引用的文档 ID,所以我假设您使用的是 displayName 作为键。将变量声明为惰性变量可让您使用其他实例变量对其进行初始化。
希望对您有所帮助。
我已经通过使用 Decodable Protocol 解决了这个问题 post;
我有一个如下所示的用户模型,它给了我一个 User
.
import UIKit
import FirebaseFirestore
protocol SerializeUser {
init?(dictionary: [String: Any])
}
struct User {
var documentRef: DocumentReference?
var displayName: String
var photoURL: String
var email: String
var isEmployee: Bool
var dictionary: [String: Any] {
return ["displayName": displayName, "photoURL": photoURL, "email": email, "isEmployee": isEmployee]
}
}
extension User: SerializeUser {
init?(dictionary: [String: Any]) {
guard
let displayName = dictionary["displayName"] as? String,
let photoURL = dictionary["photoURL"] as? String,
let isEmployee = dictionary["isEmployee"] as? Bool,
let email = dictionary["email"] as? String else { return nil }
self.init(displayName: displayName, photoURL: photoURL, email: email, isEmployee: isEmployee)
}
}
我需要以某种方式在我的 User
结构中初始化 documentRef
关于如何做到这一点的任何想法?请
在某处您需要数据库实例来构建文档引用。
var db: Firestore? = Firestore.firestore()
struct User {
lazy var documentRef: db.collection("users").document(displayName)
}
我在这里的任何地方都没有看到引用的文档 ID,所以我假设您使用的是 displayName 作为键。将变量声明为惰性变量可让您使用其他实例变量对其进行初始化。
希望对您有所帮助。
我已经通过使用 Decodable Protocol 解决了这个问题 post;