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
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]]"