swift - 将 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 。
解决方案
通读您的评论,很难理解您到底在哪里遇到问题。我假设这是因为您不知道如何编写另一个初始化程序,因为您的第一条评论:
`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)
}
推荐阅读
- ios - UIAlertController 仅在特定时间
- android - Moshi 将值反序列化为 null
- javascript - TypeError: css.eachInside 不是 gulp.task 中的函数
- vue.js - 如何确保数据在基于 API 的 Vue 应用程序上始终是最新的?
- python - 通过 POST 请求返回列表
- react-native - 使用 axios 进行昂贵的 api 调用会阻止可触摸,但在 react native 和 redux-saga 中不会使用 fetch
- javascript - Javascript 组数组
- azure-language-understanding - 在语言理解门户中禁用 LUIS 资源键
- c# - 如何从对象数组中获取键值对
- python - 使用 matplotlib 编写两个或三个 x 刻度标签,以 UT 和 MLT(磁本地时间)显示小时