Markus Gerlach
Markus Gerlach

Reputation: 121

Swift sort of array always in ascending order

i try to show a array list sorted by its Timestamp in an descending order (newest first --> highest ts first) therefore i created a downloading method and a sorting method:

 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()
}

The problem is that the values are showing always the lowest ts first no matter if i change it from self.allBlogs.sorted(by: { $0.ts! < $1.ts! }) to self.allBlogs.sorted(by: { $0.ts! > $1.ts! })

Upvotes: 0

Views: 188

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100551

You need

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

as sorted(by returns a result that you ignore it and don't re-assign it would be

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

Upvotes: 2

Related Questions