我有一个分词,看起来是这样的:
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()来玩它:
let sortedDict = dict.sort( { ($0["nausea"] as! Int) > ($1["nausea"] as! Int) })但是,很明显,它没有起作用,因为“恶心”并不是二叉神经的关键
有人能告诉我他们会怎么做吗?提前感谢!
发布于 2020-11-08 17:28:54
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)Update:更好的是,正如@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)https://stackoverflow.com/questions/64740911
复制相似问题