[英]Using Decodable to get the object and document ID with Firestore
我有一个简单的User
类,它包含以下字段:
{
"localIdentifier": "xyc9870",
"isOnline": false,
"username": "ZS"
}
我想使用Swift的Decodable
轻松地将QueryDocumentSnapshot
转换为类型安全的Swift结构。 我还想确保从QueryDocumentSnapshot
获取documentID
以便稍后更新对象。
这是我目前正在使用的解码,但显然它错过了documentId
struct User: Decodable {
let localIdentifier: String
let username: String
let isOnline: Bool
}
会喜欢这里的一只手。 谢谢!
我自己写了一个简单的便利扩展,只是将documentID
带入data
JSON,然后我可以使用下面的简单struct
extension QueryDocumentSnapshot {
func prepareForDecoding() -> [String: Any] {
var data = self.data()
data["documentId"] = self.documentID
return data
}
}
解码使用:
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: []))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.