Set is an unordered collection of unique elements, implemented as a hash table. The main difference from Array is the absence of duplicate values and the lack of order. Key interfaces: insertion methods (insert), deletion (remove), presence check (contains).
Runtime:
insert, remove, and contains work in average O(1).Example of usage:
var numbers: Set<Int> = [1, 2, 3] numbers.insert(4) // Set: 1, 2, 3, 4 numbers.insert(2) // Set remains unchanged, 2 is already present numbers.remove(1) // Set: 2, 3, 4 print(numbers.contains(3)) // true
Use Set when uniqueness is important, but order is not. Compare with Array:
Array takes O(n).Array.Set supports: ∪, ∩, −, ⊆, ⊇ and other set-theoretic operations.
Question:
Will the following code compile and why?
let set: Set = [[1, 2], [3, 4]]
Answer:
No, it will not. Set requires the element types to conform to the Hashable protocol. An array (Array) does not implement Hashable, so you cannot create sets of arrays directly. For example, Set<Int> is valid, whereas Set<[Int]> is not.
Story
In one service, developers stored unique object identifiers as [Int] rather than Set<Int>. This caused issues: presence checks and deletions were slow (time - O(n)), duplicates appeared, disrupting business logic.
Story
An attempt was made to put non-standard types in Set (for example, creating Set<MyModel>), but the type did not implement Hashable. The code compiled only after adding the appropriate protocols, but when there were errors in hash(into:), collisions and unpredictable behavior occurred during runtime.
Story
A developer expected that the order of iterating over elements in Set would match the order of insertion, and built the UI in the same order. As a result, with each run, the order was different, leading to inconsistent data presentation for end users.