You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中Int键字典排序异常,如何正确实现按键排序?

Swift字典按键排序的正确实现方法

标准的Swift Dictionary(也就是你用的[Int:String])是无序集合,不管你把排序后的键值对怎么重新插入,最终字典本身都不会保留顺序。你写的sortWithKeys函数里,虽然第一步sorted(by:)得到了有序的键值对数组,但把它们再放进新的[Int:String]字典后,顺序又丢失了,这就是结果不符合预期的核心原因。

下面给你两种可行的解决方案:

方案1:返回有序的键值对数组

既然字典本身无序,直接返回排序后的键值对数组(Array<(key: Int, value: String)>)即可,数组是有序结构,能稳定保持排序结果。修改你的函数:

func sortWithKeys(_ dict: [Int: String]) -> [(key: Int, value: String)] {
    return dict.sorted(by: { $0.key < $1.key })
}

// 调用并打印结果
let sortedPairs = sortWithKeys(monthDict)
print(sortedPairs)
// 输出会是按key从小到大排列的有序数组:[(key: 1, value: "January"), (key: 2, value: "February"), ...]

后续如果需要遍历有序的键值对,直接遍历这个数组就能满足需求。

方案2:使用有序字典OrderedDictionary

如果你需要一个既像字典一样支持通过key快速查找,又能保持插入顺序的结构,可以用Swift官方Collections库中的OrderedDictionary。

步骤如下:

  1. 先通过Swift Package Manager或CocoaPods引入Collections库
  2. 修改函数返回类型为OrderedDictionary<Int, String>,将排序后的键值对传入构造方法:
import Collections

func sortWithKeys(_ dict: [Int: String]) -> OrderedDictionary<Int, String> {
    let sortedPairs = dict.sorted(by: { $0.key < $1.key })
    return OrderedDictionary(uniqueKeysWithValues: sortedPairs)
}

// 调用并打印结果
let sortedDict = sortWithKeys(monthDict)
print(sortedDict)
// 输出会保持按键从小到大的顺序:[1: "January", 2: "February", ...]

OrderedDictionary兼具字典的高效查找特性和数组的有序性,适合既需要快速查找又需要固定顺序的场景。

内容的提问来源于stack exchange,提问作者Danya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 12:11:04