简体   繁体   English

使用Decodable通过Firestore获取对象和文档ID

[英]Using Decodable to get the object and document ID with Firestore

I have a simple User class which has the following fields: 我有一个简单的User类,它包含以下字段:

{ 
  "localIdentifier": "xyc9870",
  "isOnline": false,
  "username": "ZS"
}

I want to use Swift's Decodable to easily turn the QueryDocumentSnapshot into a type safe Swift struct. 我想使用Swift的Decodable轻松地将QueryDocumentSnapshot转换为类型安全的Swift结构。 I also want to make sure that I get the documentID from the QueryDocumentSnapshot for updating the object later. 我还想确保从QueryDocumentSnapshot获取documentID以便稍后更新对象。

This is what I'm currently using to decode but obviously it misses the documentId 这是我目前正在使用的解码,但显然它错过了documentId

struct User: Decodable {

    let localIdentifier: String
    let username: String
    let isOnline: Bool

}

Would love a hand here. 会喜欢这里的一只手。 Thanks! 谢谢!

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 我自己写了一个简单的便利扩展,只是将documentID带入data JSON,然后我可以使用下面的简单struct

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()) {
    ...
}

Edit: 编辑:

My JSONDecoder extension 我的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM