Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of items in set has been changed, Set, Swift

Tags:

ios

swift

set

Im creating 2 sets which are containing String like following

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

At first, I am thinking the order of strings in each set will be exactly as same as their orders when being added. However I was wrong about the one of set1, the console gives me this

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" { ... }

Does anyone know why the order of strings in set1 has been changed to QShift, PRN, 07:00?

like image 367
tonytran Avatar asked Sep 11 '25 20:09

tonytran


1 Answers

Because Set is an unordered data structure.

Set reference:

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.

You should take a look at NSOrderedSet class reference, for more APIs:

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

like image 109
Evgeny Karkan Avatar answered Sep 14 '25 10:09

Evgeny Karkan