[英]How to Initialize Firestore Document Reference Swift
我有一個用戶 model ,如下所示,它給了我一個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 獲取 object 和帶有 Firestore 的文檔 ID
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.