从Array Swift中删除完整的元素

时间:2018-10-05 08:28:30

标签: ios arrays swift

我正在从Firebase中读取文档并将其放入Array中。我的数组的输出是:

  

[MainApp.Message(name:Optional(“ Bluesona”),userId:   可选(“ 7epbTeafCAS51ctDxWWt0xIAWN03”),消息:可选(“”),creatAt:   可选(1535028200082),纬度:可选(“ 0.00”),经度:   Optional(“ 0.00”)),MainApp.Message(名称:Optional(“ Oliver”),userId:   可选(“ 7epbTeafCAS51ctDxWWt0xIAWN03”),消息:可选(“”),creatAt:   可选(1537440120260),纬度:可选(“ 54.976663”),经度:   Optional(“-7.732037”)),MainApp.Message(name:Optional(“ Oliver”),   userId:可选(“ 7epbTeafCAS51ctDxWWt0xIAWN03”),味精:可选(“”),   creatAt:可选(1537639139566),纬度:可选(“ 54.976726”),   经度:可选(“ -7.731986”))]

然后如何处理数组以仅显示名称为“ Bluesona”的项目?

这是我创建数组的代码

    firebaseDB.collection("message").document(key).collection("messages").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        }
        else {
            self.dataArr.removeAll()
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
                let msgdata = document.data() as! [String:Any]
                var msgObj = Message()
                if let name = msgdata["name"] as? String {

                    msgObj.name = name
                }

                if let latitude = msgdata["latitude"] as? String {

                    msgObj.latitude = latitude
                }
                if let long = msgdata["longitude"] as? String {

                    msgObj.longitude = long
                }

                if let uid = msgdata["userId"] as? String {

                    msgObj.userId = uid
                }
                if let time = msgdata["createdAt"] as? Int {

                    msgObj.creatAt = time
                }
                self.dataArr.append(msgObj)
                //                    self.dataArr.append(document.data() as [String:Any])

            }
            self.dataArr = self.dataArr.sorted(by: {$0.creatAt < $1.creatAt })
            self.tblMessage.reloadData()
            if self.dataArr.count < 1 {
                print("No Messages")
            }
            else{
            //self.tblMessage.scrollToRow(at: IndexPath(row: self.dataArr.count - 1, section: 0), at: .bottom, animated: true)
            print(self.dataArr)
            }
            }
    }

1 个答案:

答案 0 :(得分:0)

您可以使用filter实现目标。

...
self.dataArr = self.dataArr.sorted(by: {$0.creatAt < $1.creatAt })
self.dataArr = dataArr.filter { $0.name == "Bluesona"}
self.tblMessage.reloadData()
...

或者您也可以使用Swift4.2中引入的removeAll(where:)

...
self.dataArr = self.dataArr.sorted(by: {$0.creatAt < $1.creatAt })
self.dataArr.removeAll(where: { $0.name != "Bluesona"})
self.tblMessage.reloadData()
...