KevinB
KevinB

Reputation: 2484

Swift - Sort and array with [String: Int]

I'm new with swift langage and I'm trying to code a function which permits to get the 6 most popular people on my Firebase Database.

I wrote an observer which place users in an array like that:

[[userID: numberOfFollowers], [userID: numberOfFollowers], ...]

I would like to keep only the 6 users with the highest number of followers.

Do you know if it is possible?

var people = [[String: Int]]()

func loadPeople() {
  var REF_FOLLOWERS = Database.database().reference().child("followers")

  REF_FOLLOWERS.observe(.value, with: { (snapshot: DataSnapshot!) in
     print("Got snapshot")
     if let dict = snapshot.value as? [String: Any] {
        for (key, value) in dict {
           var count = 1
           if let array = value as? [String: Any] {
              for _ in array {
                 count += 1
              }
           }

           self.people.append([key : count])
           self.tableView.reloadData()
        }
     }
  })
}

Upvotes: 0

Views: 155

Answers (2)

rushisangani
rushisangani

Reputation: 3395

You could use something like:

var REF_FOLLOWERS = Database.database().reference().child("followers").queryOrdered(byChild: "numberOfFollowers").queryLimited(toFirst: 6).observe(.value, with: { (snapshot: DataSnapshot!) in {
}

This would give top 6 with the highest number of followers.

Upvotes: 3

Milan Nosáľ
Milan Nosáľ

Reputation: 19757

REF_FOLLOWERS.observe(.value, with: { (snapshot: DataSnapshot!) in
   print("Got snapshot")
   if let dict = snapshot.value as? [String: Any] {
      for (key, value) in dict {
         var count = 1
         if let array = value as? [String: Any] {
            for _ in array {
               count += 1
            }
         }

         self.people.append([key : count])
      }
   }
   // this line will sort them and return first 6
   self.people = self.people.sorted(by: { $0["numberOfFollowers"] ?? 0 > $1["numberOfFollowers"] ?? 0}).prefix(6)
   // reload data just once at the end - be efficient!
   self.tableView.reloadData()
})

Upvotes: 0

Related Questions