为什么我的SwiftUI列表填充相同的项目4次而不是全部4个?

时间:2019-11-19 02:45:19

标签: ios swift google-cloud-firestore combine swiftui-list

我正在从Firestore读取数据并将其解析为自定义模型Thought

对于我的Firestore集合中的每个文档,我都会向Thought附加一个新的@Published var thoughts对象。

struct Thought: Identifiable {

    public var id: String?
    public var name: String
    public var thought: String
    public var color: String
}

class Observer: ObservableObject {

    @Published var thoughts = [Thought]()

    init(){
        let db = Firestore.firestore()

        db.collection("thoughts")
        .addSnapshotListener { querySnapshot, error in
            guard let documents = querySnapshot?.documents else {
                print("Error fetching documents: \(error!)")
                return
            }

            for document in documents {

                var thoughtModel = Thought(id: "", name: "", thought: "", color: "")

                thoughtModel.name = document.data()["name"] as! String
                thoughtModel.thought = document.data()["thought"] as! String
                thoughtModel.color = document.data()["color"] as! String

                self.thoughts.append(thoughtModel)
            }
            print(self.thoughts) //PRINTS 4 DIFFERENT THOUGHT OBJECTS
        }
    }
}

struct ThoughtsView: View {

    @ObservedObject var observer = Observer()

    var body: some View {
        VStack {
            List {
                ForEach(self.observer.thoughts) { thought in

                    ThoughtCard(color: thought.color,
                                thought: thought.thought,
                                name: thought.name)
                    //HERE I GET THE SAME CARD 4 TIMES INSTEAD OF 4 DIFFERENT CARDS
                }
            }
        }
    }
}

打印thoughts时,我会看到Firestore数据库中当前所有的4个文档。但是,当我尝试遍历列表中的thoughts时,我只是将4个相同的Thought对象而不是4个不同的Thought对象。

我认为问题出在List之内,以及我如何遍历self.observer.thoughts,但是我不确定自己在做什么错。如何在self.observer.thoughts中用4个对象填充列表?

1 个答案:

答案 0 :(得分:0)

我的列表确实存在问题。一旦添加了base参数,List便可以识别每个id:对象并相应地显示它们。

Thought