快速排序数组总是按升序排列

时间:2019-03-09 14:16:23

标签: swift google-cloud-firestore

我尝试显示按其时间戳以降序排列的数组列表(最新的优先->最高的ts优先),因此我创建了一个下载方法和一种排序方法:

 func getBlogsByAuthor(){
    self.allBlogs.removeAll()
    for authorId in self.authorIds{
        db.collection("Blogs").whereField("authorId", isEqualTo: authorId)
            .getDocuments() { (querySnapshot, err) in
                if let err = err {
                    print("Error getting documents: \(err)")
                } else {
                    for document in querySnapshot!.documents {
                        let ts = document.get("ts") as! Int
                        let title = document.get("title") as! String
                        let body = document.get("body") as! String
                        let authorId = document.get("authorId") as! String
                        let state = document.get("stateios") as? String
                        let imageUrl = document.get("imageUrl") as! String
                        let id = document.documentID as! String
                        let blogObject  = BlogObject.init(title: title , body: body, imageUrl: imageUrl , authorId: authorId , state: state ?? "Null" , id: id, ts: ts )
                        self.allBlogs.append(blogObject)


                    }
                    self.sortDataset()

                }
        }
    }

}

func sortDataset(){
    self.allBlogs.sorted(by: { $0.ts! < $1.ts! })
    self.rv.reloadData()
}

问题在于,无论我将其从self.allBlogs.sorted(by: { $0.ts! < $1.ts! }) 更改为self.allBlogs.sorted(by: { $0.ts! > $1.ts! }) ,值始终始终显示最低的ts

1 个答案:

答案 0 :(得分:2)

您需要

self.allBlogs.sort { $0.ts! < $1.ts! } // mutating sort in place 

由于sorted(by返回的结果是您忽略了该结果,因此不必重新分配该结果

self.allBlogs = self.allBlogs.sorted(by: { $0.ts! < $1.ts! })