iOS Swift 4通过特定值对字典进行排序 [英] iOS swift 4 sort dictionary by a particular values

查看:276
本文介绍了iOS Swift 4通过特定值对字典进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您帮我对下面的字典中的值"Val1"进行排序.

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

我希望这本字典能像这样排序. "Val1"的最高值排在最前面(降序).

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

推荐答案

正如@Sulthan正确指出的,Dictionary无法排序.如果仍然愿意,您会得到Array作为结果.

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]), (键:"key1",值:["val1":1,"val2":1]), (键:"key3",值:["val1":0,"val2":9])]

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

这篇关于iOS Swift 4通过特定值对字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆