如何交换字典中的项目

how to swap items in Dictionary

我有这样的词典

let test = ["first":1,"second":2,"third":3]

我想像这样将第一项换成第三项

let test = ["third":3,"second":2,"first":1]

如何交换物品?

词典

A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering.

NSDictionary

Dictionaries Collect Key-Value Pairs. Rather than simply maintaining an ordered or unordered collection of objects, an NSDictionary stores objects against given keys, which can then be used for retrieval.

所以,答案是否定的。字典用于快速检索,您可以使用 OrderedSet 或在数组上应用您的逻辑来订购项目。

Swift 中的字典是无序集合类型。无法确定返回值的顺序。

您可以使用sorted(by:)方法对字典进行排序。结果类型将是元组数组。

let test = ["first":1,"second":2,"third":3]
//let result = test.sorted { [=10=].key > .key }
let result = test.sorted { item1, item2 in
    return item1.key > item2.key
}
print(result)//[(key: "third", value: 3), (key: "second", value: 2), (key: "first", value: 1)]