Sort Swift Array of Dictionaries by Value of a Key

前端 未结 5 1484
闹比i
闹比i 2021-02-07 05:45

I am attempting to sort a Swift array which is composed of dictionaries. I have prepared a working example below. The goal is to sort the entire array by the \"d\" element in t

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-07 05:51

    In Swift

    let mySortedArray = myArray.sorted(by: {(int1, int2)  -> Bool in
        return ((int1 as! NSDictionary).value(forKey: "d") as! Int) < ((int2 as! NSDictionary).value(forKey: "d") as! Int) // It sorted the values and return to the mySortedArray
      }) 
    
    print(mySortedArray)
        
    myArray.removeAllObjects() // Remove all objects and reuse it
        
    myArray.addObjects(from: mySortedArray)
        
    print(mySortedArray)
    

    it is easy to arrange the array of dictionary value in ascending order. It doesn't need any loops.

提交回复
热议问题