A Set in Swift is an unordered collection of unique elements. Unlike an Array, it does not allow duplicate values and does not maintain the order of elements.
var fruits: Set<String> = ["Apple", "Banana", "Cherry"]
print(fruits)
//Output
["Cherry", "Apple", "Banana"] // Order may vary
Key Set Operations
//Adding an Element
fruits.insert("Mango")
print(fruits)
//Output
["Cherry", "Apple", "Mango", "Banana"]
//Removing an Element
fruits.remove("Banana")
print(fruits)
//Output
fruits.remove("Banana")
print(fruits)
Set Operations
1. Union
Combines all unique elements from two sets.
let setA: Set = [1, 2, 3]
let setB: Set = [3, 4, 5]
let unionSet = setA.union(setB)
print(unionSet)
//Output
[1, 2, 3, 4, 5]
2.Intersection
Finds common elements between two sets.
let intersectionSet = setA.intersection(setB)
print(intersectionSet)
//Output
[3]
Difference Between Sets and Arrays
Feature | Set | Array |
---|---|---|
Order | Unordered | Ordered |
Duplicates | Not allowed | Allowed |
Performance | Faster for lookups and operations | Slower for lookups (O(n)) |
Use Case | Ensuring unique values, mathematical operations | Sequential data, maintaining order |