Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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) 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.
// Initializing an empty set
var emptyIntSet = Set<Int>()
// Initializing with an array literal using explicit type annotation
var stringSet: Set<String> = ["Apple", "Banana", "Cherry"]
// Initializing with type inference (type is inferred as Set<Double>)
var doubleSet: Set = [1.5, 2.0, 3.14]
Core Properties and Inspection
Sets provide standard collection properties to inspect their state and contents.
let count = stringSet.count // Returns the number of elements
let isEmpty = stringSet.isEmpty // Returns a Boolean indicating if count == 0
// Constant-time O(1) membership check
let containsApple = stringSet.contains("Apple")
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.
// Insertion returns a tuple: (inserted: Bool, memberAfterInsert: Element)
let insertResult = stringSet.insert("Date")
// insertResult.inserted is true if "Date" was not already in the set
// Removal returns an Optional containing the removed element, or nil if not found
let removedElement = stringSet.remove("Banana")
// Removes all elements, optionally keeping the allocated capacity
stringSet.removeAll(keepingCapacity: true)
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.
let setA: Set = [1, 2, 3, 4]
let setB: Set = [3, 4, 5, 6]
// Union: Elements in either set
let unionSet = setA.union(setB)
// Result: [1, 2, 3, 4, 5, 6] (unordered)
// Intersection: Elements common to both sets
let intersectionSet = setA.intersection(setB)
// Result: [3, 4]
// Subtracting: Elements in setA that are not in setB
let differenceSet = setA.subtracting(setB)
// Result: [1, 2]
// Symmetric Difference: Elements in either set, but not both
let symmetricDiffSet = setA.symmetricDifference(setB)
// Result: [1, 2, 5, 6]
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.
let setC: Set = [1, 2]
// Subset: All elements of setC are contained in setA
let isSubset = setC.isSubset(of: setA) // true
// Superset: setA contains all elements of setC
let isSuperset = setA.isSuperset(of: setC) // true
// Strict Subset/Superset: Subset/Superset, but the sets are not equal
let isStrictSubset = setC.isStrictSubset(of: setA) // true
// Disjoint: The sets have no elements in common
let isDisjoint = setC.isDisjoint(with: setB) // true
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.
// Unordered iteration
for number in setA {
print(number)
}
// Ordered iteration (returns an Array)
for number in setA.sorted() {
print(number)
}
Master Swift with Deep Grasping Methodology!Learn More