首页 > 解决方案 > 将 dosumentSnapshot 分配给自定义对象?

问题描述

首先,我看到了答案: 在这里, 但对我来说,来自 android 和 angular 的我不得不编写这么多代码(在 android 和 angular 中需要一行)加上答案不是最新的,所以想知道是否现在有更好的方法

为了澄清,这里是我的例子:

struct User{
  let fistName:String
  let lastName:String
}

我用以下方式检索数据:

Firestoer.firestore().collection("users").document('someId').getDocument{
   (snapshot,error) in 
}

问题是如何通过一行代码将快照值分配给用户对象值——比如 user = snapshot -ish 。

标签: swiftfirebasegoogle-cloud-firestore

解决方案


通读您的评论,很难理解您到底在哪里遇到问题。我假设这是因为您不知道如何编写另一个初始化程序,因为您的第一条评论:

`my object is simple "stuct" and I could not make "(dictionary: data)" -call.`

这是您可以使用的初始化程序:

extension User {
    init?(dictionary: [String: Any]){
        guard let firstName = dictionary["firstName"] as? String else { return nil }
        guard let lastName = dictionary["lastName"] as? String else { return nil }
    }
        self.init(firstName: firstName, lastName: lastName)
}

推荐阅读