LoginSignup
0
1

More than 3 years have passed since last update.

Cannot convert value of type 'DocumentSnapshot' to expected argument type 'QueryDocumentSnapshot'

Posted at

QueryDocumentSnapshotからモデルをインスタンス化していたので、DocumentSnapshotから生成しようとするとエラーが出た。

DocumentSnapshotとQueryDocumentSnapshotの違い

こちらの記事が分かりやすい。
https://note.com/shion_consul/n/nd45e9f385696

DocumentSnapshotは.getDocument()で取得する単一のデータ。ただし存在の保証はない。
QuerySnapshotはdb.collection("posts").addEventLitener()などで取得してきたドキュメントの塊で、その一つ一つがQueryDocumentSnapshotである。QueryDocumentSnapshotはQueySnapshotの子なので存在の保証がされているっぽい。

本題

私のケースですとQueryDocumentSnapshotを使ってModelからインスタンスを生成していたのですが、QueryDocumentSnapshotはDocumentSnapshotを継承したクラスだったので以下のようにするとエラーは消えました。

struct Post {
   var name: String?

   init(document: DocumentSnapshot) {
        guard let data = document.data() else { return } // ここはあまり良くない書き方だと思う
        if let name = data["name"] as? String {
            self.name = name
        }
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1