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