繁体   English   中英

如何初始化 Firestore 文档参考 Swift

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM