iOS swift 4 sort dictionary by a particular values

余生长醉 提交于 2020-01-07 09:42:28

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/54732911/ios-swift-4-sort-dictionary-by-a-particular-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!