Skip to main content
A Set in Swift is a generic, unordered collection that stores distinct values of the same type. To be stored in a set, a type must conform to the Hashable protocol, which allows the collection to compute a hash value for each element. This hash value guarantees uniqueness and enables O(1)O(1) constant-time complexity for lookups, insertions, and deletions.

Initialization

Because Swift’s array literals are used to initialize both arrays and sets, you must explicitly declare the Set type to prevent the compiler from inferring an Array.

Core Properties and Inspection

Sets provide standard collection properties to inspect their state and contents.

Mutating Operations

When modifying a set, operations often return tuples or optionals to indicate the success of the mutation or the previous state of the collection.

Fundamental Set Operations

Swift provides built-in methods to perform mathematical set operations. These methods return a new Set and do not mutate the original collections.
Note: Swift also provides mutating equivalents for these operations: formUnion(), formIntersection(), subtract(), and formSymmetricDifference().

Set Comparison and Equality

Sets can be compared using standard equality operators or specific relational methods. Two sets are considered equal if they contain the exact same elements, regardless of internal memory order.

Iteration

Because sets are unordered, iterating over a Set does not guarantee any specific sequence. To iterate in a predictable order, use the sorted() method, which returns an Array of the set’s elements sorted by their < operator.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More