使用 Swift Codable 解码 firestore 文档时获取文档 ID

one*_*uan 3 ios swift codable google-cloud-firestore

我正在使用一个类来解码检索到的 firestore 文档,如果我不想操作数据,它会按预期工作:

class Room: Identifiable, Codable {

    @DocumentID public var id:String?
    var name:String

}
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试使用自己的 init 来设置值,我无法获取 firestore 文档 ID?

class Room: Identifiable, Codable {

    @DocumentID public var id:String?
    var name:String
    
    
    enum Keys:String, CodingKey {
        case name
        case capacity
        case photo = "url"
    }
    
    required init(from decoder: Decoder) throws {

        // How do I get the document ID to set the id value?

        let container = try decoder.container(keyedBy: Keys.self)
        name = try container.decode(String.self, forKey: .name)
        capacity = try container.decode(Int.self, forKey: .capacity)
        photo = try container.decode(String.self, forKey: .photo)

        // Do some more stuff here...
    }
}
Run Code Online (Sandbox Code Playgroud)

one*_*uan 6

在其他地方找到了答案,这非常有效。为其他带着相同问题到达这里的人发帖。

长话短说——

使用以下代码来解码 init 函数中的 DocumentReference:

ref = try container.decode(DocumentID<DocumentReference>.self, forKey: .ref)
  .wrappedValue
Run Code Online (Sandbox Code Playgroud)

更长的解释:我不会假装100%理解这一点,但这里有一个很好的解释https://github.com/firebase/firebase-ios-sdk/issues/7242