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
- 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).
- Sort entries by key: Take those processed key-value pairs and sort them alphabetically by their string keys.
- Build the ordered dictionary: Convert the sorted entries back into a dictionary. Since Swift 5.1, the standard
Dictionarypreserves 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()withvalues.sorted(by: >).
内容的提问来源于stack exchange,提问作者Nassif
相关产品推荐
相关产品推荐

