首页 > 解决方案 > Swift:追加到字典中返回随机

问题描述

我使用这段代码:

AppDelegate.monthList = [Int: String]()
for index in stride(from: 1, to: 12, by: 1) {
    AppDelegate.monthList[index] = "\(index)"
}

print("iosLog MONTH: \(AppDelegate.monthList)")

结果是:

iosLog MONTH:[11:“11”,10:“10”,2:“2”,4:“4”,9:“9”,5:“5”,6:“6”,7:“7 ", 3: "3", 1: "1", 8: "8"]

为什么?!

我想分别添加键(如PHPJava

标签: arraysswiftxcodedictionary

解决方案


因为Dictionary无序集合:

每个字典都是键值对的无序集合。

因此,如果您的目标是获得它的排序版本,您应该 - 从逻辑上 - 将其转换为有序集合,即数组。你可以得到:

AppDelegate.monthList排序后的键数组:

let sortedkeys = AppDelegate.monthList.keys.sorted()
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

排序后的AppDelegate.monthList值数组:

let sortedValues = AppDelegate.monthList.values.sorted()
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

或排序的元组数组,如[(key, value)]

let sortedTuples = AppDelegate.monthList.sorted(by: <)

for tuple in sortedTuples {
    print("\(tuple.key): \(tuple.value)")
}

推荐阅读