Sort Swift Array of Dictionaries by Value of a Key

前端 未结 5 1481
闹比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 06:05

    when we parse the data then we can sort by using NSSortDescriptor

    let dataDict1 = responseDict.valueForKey("Data")
    self.customerArray = dataDict1!.valueForKey("Customers") as! NSMutableArray
    
    var tempArray = NSMutableArray()
    for  index in self.customerArray {
       tempArray.addObject(index.valueForKey("Customer") as! NSMutableDictionary)
    }
    
    let descriptor: NSSortDescriptor =  NSSortDescriptor(key: "name", ascending: true, selector: "caseInsensitiveCompare:")
    let sortedResults: NSArray = tempArray.sortedArrayUsingDescriptors([descriptor])
    self.customerArray = NSMutableArray(array: sortedResults)
    

提交回复
热议问题