使用Decodable在Firestore中获取对象和文档ID [英] Using Decodable to get the object and document ID with Firestore
问题描述
我有一个简单的User
类,其中包含以下字段:
I have a simple User
class which has the following fields:
{
"localIdentifier": "xyc9870",
"isOnline": false,
"username": "ZS"
}
我想使用Swift的Decodable
轻松地将QueryDocumentSnapshot
转换为类型安全的Swift结构.我还想确保从QueryDocumentSnapshot
获取documentID
以便以后更新对象.
I want to use Swift's Decodable
to easily turn the QueryDocumentSnapshot
into a type safe Swift struct. I also want to make sure that I get the documentID
from the QueryDocumentSnapshot
for updating the object later.
这是我目前用于解码的内容,但是显然它错过了documentId
This is what I'm currently using to decode but obviously it misses the documentId
struct User: Decodable {
let localIdentifier: String
let username: String
let isOnline: Bool
}
在这里愿意帮忙.谢谢!
Would love a hand here. Thanks!
推荐答案
我为自己编写了一个小的便捷扩展,将documentID
引入了data
JSON,然后可以使用下面的简单struct
>
I wrote myself a small convenience extension that just brings the documentID
into the data
JSON and then I can use the simple struct
below
extension QueryDocumentSnapshot {
func prepareForDecoding() -> [String: Any] {
var data = self.data()
data["documentId"] = self.documentID
return data
}
}
使用以下代码进行解码:
Decode using:
struct User: Decodable {
let documentId: String
let localIdentifier: String
let username: String
let isOnline: Bool
}
if let user = try? JSONDecoder().decode(User.self, fromJSONObject: doc.prepareForDecoding()) {
...
}
我的JSONDecoder
扩展名
extension JSONDecoder {
func decode<T>(_ type: T.Type, fromJSONObject object: Any) throws -> T where T: Decodable {
return try decode(T.self, from: try JSONSerialization.data(withJSONObject: object, options: []))
}
}
这篇关于使用Decodable在Firestore中获取对象和文档ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!