Lesson 23Collections
Sets
Unique Collections
Sets store unique values of the same type with no defined order. They're perfect when you need to ensure no duplicates!
Sets vs Arrays
Array
- Ordered
- Allows duplicates
- Access by index
- [1, 2, 2, 3]
Set
- Unordered
- No duplicates
- Fast lookup
- {1, 2, 3}
Creating Sets
var colors: Set<String> = ["Red", "Blue"]
let numbers: Set = [1, 2, 3]
var empty = Set<Int>()
Common Operations
.insert()Add element
.remove()Remove element
.contains()Check existence
.countNumber of items
.isEmptyCheck if empty
.sorted()Get sorted array
When to Use Sets
- Remove duplicates from a list
- Check if an item exists (very fast!)
- Compare collections (union, intersection)
- Track unique visitors, IDs, tags, etc.
main.swift
// Creating sets
var colors: Set<String> = ["Red", "Green", "Blue"]
let numbers: Set = [1, 2, 3, 4, 5]
// Empty set
var emptySet = Set<Int>()
// Sets have NO duplicates!
var scores: Set = [85, 90, 85, 92, 90]
print(scores) // [85, 90, 92] - duplicates removed!
// Sets are UNORDERED
// The order may be different each time
// Adding elements
colors.insert("Yellow")
print(colors)
// Removing elements
let removed = colors.remove("Red")
print("Removed: \(removed ?? "Nothing")")
// Checking membership
print(colors.contains("Blue")) // true
print(colors.contains("Red")) // false (we removed it)
// Set properties
print("Count: \(colors.count)")
print("Is empty: \(colors.isEmpty)")
// Converting array to set (removes duplicates)
let duplicates = [1, 2, 2, 3, 3, 3, 4]
let uniqueNumbers = Set(duplicates)
print(uniqueNumbers) // {1, 2, 3, 4}
// Converting set back to array
let numbersArray = Array(uniqueNumbers)
print(numbersArray)
// Iterating through a set
for color in colors {
print(color)
}
// Sorted iteration
for color in colors.sorted() {
print(color)
}
// Creating set from characters
let text = "hello"
let uniqueChars = Set(text)
print(uniqueChars) // {"h", "e", "l", "o"}Try It Yourself!
Create an array with duplicate numbers, convert it to a set to remove duplicates, then convert back to a sorted array!