ios - 集合中项目的顺序已更改,Set,Swift

标签 ios swift set

我正在创建 2 个包含 String 的集合,如下所示

 let set1 : Set<String>   =   (["07:00", "QShift", "PRN"])
 let set2 : Set<String>   =   (["07:15", "QShift", "PRN"])

起初,我认为每个集合中字符串的顺序将与它们添加时的顺序完全相同。但是我对 set1 中的一个是错误的,控制台给了我这个

Printing description of set1:
▿ 3 elements
  - [0] : "QShift"
  - [1] : "PRN"
  - [2] : "07:00" { ... }

Printing description of set2:
▿ 3 elements
  - [0] : "07:15"
  - [1] : "QShift"
  - [2] : "PRN" { ... }

有谁知道为什么 set1 中的字符串顺序已更改为 QShift, PRN, 07:00

最佳答案

因为Set是一个无序的数据结构。

Set引用:

A set stores distinct values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once.

你应该看看NSOrderedSet类引用,更多 API:

NSOrderedSet and its subclass, NSMutableOrderedSet, declare the programmatic interfaces to an ordered collection of objects.

关于ios - 集合中项目的顺序已更改,Set,Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38556070/

相关文章:

java - Collections.sort(list) 不适用于(链接的)哈希集背后的原因?

algorithm - 公平产品分配算法

ios - UIImagePickerController 的图像是否可能没有 CGImage 值?

ios - 从 subview 返回时 Viewdidappear 不会调用

ios - Tableview 中的文本字段在 iOS 9 和 iOS10 上的行为有所不同

ios - 终止应用程序的本地横幅通知

mysql - 将列值从一个表复制到另一个匹配的 ID - SQLite

ios - 写入扩展文件属性

iOS - 尝试实现动画时钟 : Unable to simultaneously satisfy constraints runtime error -noob level 99

ios - xcode swift 如何调试应用程序关闭后崩溃的原因