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

Swift中如何对字典按键排序并同步排序对应数组值

Solution in Swift

To get your dictionary sorted by keys with each corresponding array value also sorted, here's a straightforward approach tailored to Swift:

Step-by-Step Breakdown

  1. Sort each value array: For every entry in your original dictionary, we’ll sort the integer array in ascending order (easy to adjust if you need descending).
  2. Sort entries by key: Take those processed key-value pairs and sort them alphabetically by their string keys.
  3. Build the ordered dictionary: Convert the sorted entries back into a dictionary. Since Swift 5.1, the standard Dictionary preserves insertion order when using unique keys, so your sorted order will stay intact when you iterate over it.

Full Code Implementation

var dicNumArray: Dictionary<String, [Int]> = ["q":[4,3,2,1,5],"a":[2,3,4,5,5],"s":[123,123,132,43,4],"t":[0,88,66,542,321]]

// Process and sort the dictionary in one chain
let sortedDictionary = Dictionary(uniqueKeysWithValues:
    dicNumArray.map { (key, values) in
        (key, values.sorted()) // Sort each array's integers
    }
    .sorted { $0.0 < $1.0 } // Sort entries by key in ascending order
)

// Verify the result
print(sortedDictionary)

Expected Result

When you run this code, you’ll get the following output:

["a": [2, 3, 4, 5, 5], "q": [1, 2, 3, 4, 5], "s": [4, 43, 123, 123, 132], "t": [0, 66, 88, 321, 542]]

Quick Customizations

  • Reverse key order: To sort keys from Z to A, change the sorted closure to $0.0 > $1.0.
  • Reverse array order: To sort each integer array from largest to smallest, replace values.sorted() with values.sorted(by: >).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:10:16