Monday, January 23, 2017

Swift 3.0 Sorting Dictionary based on values

In my Objective C Sorting NSDictionary based on Values tutorial, I have explained Dictionary sorting based on values using Objective C. In this tutorial let's see the same functionality using Swift 3.0.

  
   let isAscending = false

   let dict = [

          "AAAA" : Int(2500),
          "BBBB" : Int(3200),
          "CCCC" : Int(2800),
          "DDDD" : Int(1200)

   ]


I have taken a Dictionary with keys as Strings and values as Ints. I have also taken a flag(isAscending) to configure the order.

  
    let sortedDict = dict.sorted {(_ obj1: (key1: String, value1: Int), 
                                              _ obj2: (key2: String, value2: Int)) -> Bool in
    
         let val1 = (obj1.value1)
         let val2 = (obj2.value2)
    
         if (isAscending) {

             if((val1 < val2)) {
                return true
              }

         }

         else {

             if((val1 > val2)) {
                return true
            }

         }
    
      return false
    
  }


  print (sortedDict)

  isAscending = false  :- [("BBBB", 3200), ("CCCC", 2800), ("AAAA", 2500), ("DDDD", 1200)]
  isAscending = true   :- [("DDDD", 1200), ("AAAA", 2500), ("CCCC", 2800), ("BBBB", 3200)]
       




Hope this post is useful. Feel free to comment incase of any queries.