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
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.
To declare, if you need to keep it as AnyObject, you have to explicitly cast:
var myArray = Array<AnyObject>()
var dict = Dictionary<String, AnyObject>()
dict["a"] = ("hickory" as! AnyObject)
dict["b"] = ("dickory" as! AnyObject)
dict["c"] = ("dock" as! AnyObject)
dict["d"] = (6 as! AnyObject)
myArray.append(dict as! AnyObject)
dict["a"] = ("three" as! AnyObject)
dict["b"] = ("blind" as! AnyObject)
dict["c"] = ("mice" as! AnyObject)
dict["d"] = (5 as! AnyObject)
myArray.append(dict as! AnyObject)
dict["a"] = ("larry" as! AnyObject)
dict["b"] = ("moe" as! AnyObject)
dict["c"] = ("curly" as! AnyObject)
dict["d"] = (4 as! AnyObject)
myArray.append(dict as! AnyObject)
Without appending, you can do it like this:
var myArray: [AnyObject] = [ ([
"a" : ("hickory" as! AnyObject),
"b" : ("dickory" as! AnyObject),
"c" : ("dock" as! AnyObject),
"d" : (6 as! AnyObject)
] as! AnyObject), ([
"a" : ("three" as! AnyObject),
"b" : ("blind" as! AnyObject),
"c" : ("mice" as! AnyObject),
"d" : (5 as! AnyObject)
] as! AnyObject), ([
"a" : ("larry" as! AnyObject),
"b" : ("moe" as! AnyObject),
"c" : ("curly" as! AnyObject),
"d" : (4 as! AnyObject)
] as! AnyObject)
]
Which gives you the same result. Although, if only the value object in the dictionary needs to change, you don't need to cast the elements of the array:
var myArray: [Dictionary<String, AnyObject>] = [[
"a" : ("hickory" as! AnyObject),
"b" : ("dickory" as! AnyObject),
"c" : ("dock" as! AnyObject),
"d" : (6 as! AnyObject)
], [
"a" : ("three" as! AnyObject),
"b" : ("blind" as! AnyObject),
"c" : ("mice" as! AnyObject),
"d" : (5 as! AnyObject)
], [
"a" : ("larry" as! AnyObject),
"b" : ("moe" as! AnyObject),
"c" : ("curly" as! AnyObject),
"d" : (4 as! AnyObject)
]
]
Then, to sort, you use the sort() closure, which sorts an Array in place. The closure you supply takes two arguments (named $0 and $1), and returns a Bool. The closure should return true if $0 is ordered before $1, or false if it comes after. To do this, you've got to cast an awful lot:
//myArray starts as: [
// ["d": 6, "b": "dickory", "c": "dock", "a": "hickory"],
// ["d": 5, "b": "blind", "c": "mice", "a": "three"],
// ["d": 4, "b": "moe", "c": "curly", "a": "larry"]
//]
myArray.sort{
(($0 as! Dictionary<String, AnyObject>)["d"] as? Int) < (($1 as! Dictionary<String, AnyObject>)["d"] as? Int)
}
//myArray is now: [
// ["d": 4, "b": "moe", "c": "curly", "a": "larry"],
// ["d": 5, "b": "blind", "c": "mice", "a": "three"],
// ["d": 6, "b": "dickory", "c": "dock", "a": "hickory"]
//]
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)
edit/update: Xcode 11 • Swift 5
var array: [[String:Any]] = []
var dict: [String: Any] = [:]
dict["a"] = "hickory"
dict["b"] = "dickory"
dict["c"] = "dock"
dict["d"] = 5
array.append(dict)
dict["a"] = "three"
dict["b"] = "blind"
dict["c"] = "mice"
dict["d"] = 6
array.append(dict)
dict["a"] = "larry"
dict["b"] = "moe"
dict["c"] = "curly"
dict["d"] = 2
array.append(dict)
let sortedArray = array.sorted { $0["d"] as? Int ?? .zero < $1["d"] as? Int ?? .zero }
print(sortedArray) // "[[b: moe, a: larry, d: 2, c: curly], [b: dickory, a: hickory, d: 5, c: dock], [b: blind, a: three, d: 6, c: mice]]"
Sort Array of Dictionary in Swift 3 & 4
let sortedResults = (userArray as NSArray).sortedArray(using: [NSSortDescriptor(key: "name", ascending: true)]) as! [[String:AnyObject]]