首页 > 解决方案 > iOS swift 4 sort dictionary by a particular values

问题描述

Can you please help me sorting the dictionary below with value "Val1".

var data = ["key1" : ["val1": 1,"val2": 1],
            "key2" : ["val1": 5,"val2": 2],
            "key3" : ["val1": 0,"val2": 9]]

I am expecting this dictionary to be sorted like this. Highest values of 'Val1' to be on top (descending order)..

var data = [ "key2" : ["val1": 5,"val2": 2],
             "key1" : ["val1": 1,"val2": 1],
             "key3" : ["val1": 0,"val2": 9]]

标签: iosswiftsortingdictionary

解决方案


As @Sulthan correctly pointed out Dictionary cannot be sorted. If you still want to, you'll get an Array as result.

let data = [
    "key1": ["val1": 1,"val2": 1],
    "key2": ["val1": 5,"val2": 2],
    "key3": ["val1": 0,"val2": 9]
]

let result = data.sorted { $0.1["val1"]! > $1.1["val1"]! }
print(result)

[(key: "key2", value: ["val1": 5, "val2": 2]), (key: "key1", value: ["val1": 1, "val2": 1]), (key: "key3", value: ["val1": 0, "val2": 9])]


推荐阅读