arrays - 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"]
为什么?!
我想分别添加键(如PHP
或Java
)
解决方案
因为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)")
}
推荐阅读
- javascript - 如何选择具有三元条件的默认下拉选项?
- r - 具有可变治疗交互作用的每个治疗组的 C 指数
- bash - 带有数组的 Bash 脚本
- php - 后台进程在 5 分钟后停止 - PHP 和 WordPress
- file - 在 Angular 9 中单击链接时下载文件?
- android - 如何使用android studio创建平板电脑背景
- php - 按字母数字值对二维数组进行排序,例如 1、1b、1x、3、2a、1c
- flutter - 为什么 onTap 在我的火焰游戏 (Flutter) 中不起作用?
- java - HikariCP 连接池多租户数据源
- javascript - AngularJS - 数据不会从存储过程中拉回表中