按值对字典[键:[键:值]]进行排序-Swift

按值对字典[键:[键:值]]进行排序-Swift,swift,sorting,dictionary,Swift,Sorting,Dictionary,我有一个口述,看起来像这样: var dict = [Int: [String: Any]]() dict[1] = ["nausea": 23, "other": "hhh"] dict[2] = ["nausea": 3, "other": "kkk"] dict[3] = ["nausea": 33, "other" : &qu

我有一个口述,看起来像这样:

var dict = [Int: [String: Any]]()

dict[1] = ["nausea": 23, "other": "hhh"]
dict[2] = ["nausea": 3, "other": "kkk"]
dict[3] = ["nausea": 33,  "other" : "yyy"]
sortedDict = [2: ["nausea": 3, "other": "kkk"], 1: ["nausea": 23, "other": "hhh"], 3: ["nausea": 33,  "other" : "yyy"]]
我想根据关键字“恶心”的字典值从最小到最大对字典进行排序

看起来像这样:

var dict = [Int: [String: Any]]()

dict[1] = ["nausea": 23, "other": "hhh"]
dict[2] = ["nausea": 3, "other": "kkk"]
dict[3] = ["nausea": 33,  "other" : "yyy"]
sortedDict = [2: ["nausea": 3, "other": "kkk"], 1: ["nausea": 23, "other": "hhh"], 3: ["nausea": 33,  "other" : "yyy"]]
我尝试使用.sort()来处理它:

但是,很明显,它不起作用,因为“恶心”不是口述的关键

有人能告诉我他们会怎么做吗?
提前谢谢

A
Dictionary
在设计上是无序的,如以下明确说明:

每个字典都是一个无序的键值对集合

您可能正在寻找一种有序类型,如
Array

var arrayDict = [
    ["nausea": 23, "other": "hhh"],
    ["nausea": 3, "other": "kkk"],
    ["nausea": 33,  "other" : "yyy"]
]

let sorted = arrayDict.sorted { $0["nausea"] as! Int < $1["nausea"] as! Int }
print(sorted)
var arrayDict=[
[“恶心”:23,“其他”:“hhh”],
[“恶心”:3,“其他”:“kkk”],
[“恶心”:33,“其他”:“yyy”]
]
设sorted=arrayDict.sorted{$0[“恶心”]as!Int<$1[“恶心”]as!Int}
打印(已排序)
更新:正如@LeoDabus在评论中建议的那样,您可以使用自定义对象数组:

struct MyObject {
    var nausea: Int
    var other: String
}
var array = [
    MyObject(nausea: 23, other: "hhh"),
    MyObject(nausea: 3, other: "kkk"),
    MyObject(nausea: 33, other: "yyy")
]

let sorted = array.sorted { $0.nausea < $1.nausea }
print(sorted)
struct MyObject{
变量:Int
变量其他:字符串
}
变量数组=[
MyObject(恶心:23,其他:“hhh”),
MyObject(恶心:3,其他:“kkk”),
MyObject(恶心:33,其他:“yyy”)
]
设sorted=array.sorted{$0.0<$1.0}
打印(已排序)

字典是无序的数据结构。如果需要排序,则必须使用数组。这仍然是一种丑陋的方法。OP应该使用自定义对象数组。@LeoDabus我更新了我的答案。你完全正确,它更优雅。@leoDabus是的,这是真的。刚刚在我的应用程序中实现了它,它还修复了我昨天第二篇文章的另一个问题。对此我深表歉意。。。