程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用 Swift Codable 解码 Firestore 文档时获取文档 ID大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用 Swift Codable 解码 Firestore 文档时获取文档 ID?

开发过程中遇到使用 Swift Codable 解码 Firestore 文档时获取文档 ID的问题如何解决?下面主要结合日常开发的经验,给出你关于使用 Swift Codable 解码 Firestore 文档时获取文档 ID的解决方法建议,希望对你解决使用 Swift Codable 解码 Firestore 文档时获取文档 ID有所启发或帮助;

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

class Room: IDentifiable,Codable {

    @documentID public var ID:string?
    var name:string

}

但是,如果我尝试使用自己的 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...
    }
}

解决方法

在别处找到了答案,这很完美。为其他任何带着相同查询来到这里的人发帖。

TL;DR -

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

ref = try container.decode(DocumentID<DocumentReference>.self,forKey: .ref)
  .wrappedValue

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

大佬总结

以上是大佬教程为你收集整理的使用 Swift Codable 解码 Firestore 文档时获取文档 ID全部内容,希望文章能够帮你解决使用 Swift Codable 解码 Firestore 文档时获取文档 ID所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。