Sort Swift Array of Dictionaries by Value of a Key

前端 未结 5 1490
闹比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条回答
  •  猫巷女王i
    2021-02-07 06:06

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

提交回复
热议问题