Sets are a fundamental collection type in Swift, offering an unordered group of unique elements. They provide efficient operations for managing distinct values, making them ideal for tasks requiring uniqueness and fast membership testing.
In Swift, you can create sets using array literals or the Set type explicitly:
let fruits: Set<String> = ["Apple", "Banana", "Orange"]
var numbers = Set([1, 2, 3, 4, 5])
Sets automatically remove duplicate elements, ensuring uniqueness:
let uniqueNumbers = Set([1, 2, 2, 3, 3, 3])
print(uniqueNumbers) // Prints: [2, 3, 1]
Swift provides various methods for working with sets:
insert(_:)
: Add an elementremove(_:)
: Remove an elementcontains(_:)
: Check for an elementExample usage:
var colors = Set(["Red", "Green", "Blue"])
colors.insert("Yellow")
colors.remove("Green")
print(colors.contains("Blue")) // Prints: true
Sets in Swift support powerful algebraic operations:
union(_:)
: Combine two setsintersection(_:)
: Find common elementssubtracting(_:)
: Remove elements from another setsymmetricDifference(_:)
: Elements in either set, but not bothThese operations are particularly useful when working with multiple sets:
let evens = Set([2, 4, 6, 8])
let odds = Set([1, 3, 5, 7])
let primes = Set([2, 3, 5, 7])
let unionSet = evens.union(odds)
let intersectionSet = evens.intersection(primes)
let differenceSet = odds.subtracting(primes)
Sets offer excellent performance for certain operations:
However, sets sacrifice ordered access, which is available in Swift Arrays.
Understanding Swift sets enhances your ability to work with collections efficiently. They complement other Swift data structures, providing unique capabilities for managing distinct elements.
To further expand your Swift knowledge, explore these related topics: