Skip to main content

Swift Sets

Introduction

Sets are one of the fundamental collection types in Swift, alongside Arrays and Dictionaries. A Set is an unordered collection of unique values of the same type. Think of a Set as a container where each item can appear only once, and the order doesn't matter.

Sets are particularly useful when:

  • You need to ensure uniqueness of elements
  • You want to quickly check if an element exists
  • You need to perform mathematical set operations like union, intersection, and difference

In this lesson, we'll explore how to create, modify, and work with Sets in Swift, and see practical examples of when and why you might use them.

Creating Sets

Basic Set Creation

You can create a set using the Set type with array literal syntax:

swift
// Creating a set of strings
let fruits: Set<String> = ["Apple", "Orange", "Banana", "Mango"]

// Swift can infer the type
var colors = Set(["Red", "Green", "Blue"])

Creating an Empty Set

To create an empty set, you need to specify its type:

swift
var emptySet = Set<Int>()

Adding Elements to a Set

swift
var programmingLanguages = Set<String>()
programmingLanguages.insert("Swift")
programmingLanguages.insert("Python")
programmingLanguages.insert("JavaScript")
programmingLanguages.insert("Swift") // This won't add a duplicate

print(programmingLanguages)
// Output: ["JavaScript", "Swift", "Python"] (order may vary)

Set Properties and Methods

Checking Basic Properties

swift
let numbers: Set = [1, 2, 3, 4, 5]

print("Count: \(numbers.count)") // Output: Count: 5
print("Is empty: \(numbers.isEmpty)") // Output: Is empty: false

Checking for Elements

swift
let fruitSet: Set = ["Apple", "Orange", "Banana"]

if fruitSet.contains("Apple") {
print("The set contains Apple")
} else {
print("The set does not contain Apple")
}
// Output: The set contains Apple

if fruitSet.contains("Grape") {
print("The set contains Grape")
} else {
print("The set does not contain Grape")
}
// Output: The set does not contain Grape

Iterating Through a Set

swift
let planets: Set = ["Mercury", "Venus", "Earth", "Mars", "Jupiter"]

for planet in planets {
print(planet)
}
// Output (order may vary):
// Venus
// Earth
// Jupiter
// Mercury
// Mars

// Sorted iteration
for planet in planets.sorted() {
print(planet)
}
// Output (alphabetical order):
// Earth
// Jupiter
// Mars
// Mercury
// Venus

Modifying Sets

Adding and Removing Elements

swift
var mutableSet: Set = [1, 2, 3]

// Adding elements
mutableSet.insert(4)
print(mutableSet) // Output: [1, 2, 3, 4] (order may vary)

// Removing elements
mutableSet.remove(2)
print(mutableSet) // Output: [1, 3, 4] (order may vary)

// Remove all elements
mutableSet.removeAll()
print(mutableSet) // Output: []

Updating with Another Set

swift
var original: Set = [1, 2, 3]
let newElements: Set = [3, 4, 5]

// Update original set to include all elements from newElements
original.formUnion(newElements)
print(original) // Output: [1, 2, 3, 4, 5] (order may vary)

Set Operations

One of the most powerful features of Sets is the ability to perform mathematical set operations.

Union

The union of two sets contains all the elements from both sets:

swift
let setA: Set = [1, 2, 3, 4]
let setB: Set = [3, 4, 5, 6]

let union = setA.union(setB)
print(union) // Output: [1, 2, 3, 4, 5, 6] (order may vary)

Intersection

The intersection contains only elements that are in both sets:

swift
let intersection = setA.intersection(setB)
print(intersection) // Output: [3, 4] (order may vary)

Subtraction

The subtraction of one set from another contains elements that are in the first set but not in the second:

swift
let subtraction = setA.subtracting(setB)
print(subtraction) // Output: [1, 2] (order may vary)

Symmetric Difference

The symmetric difference contains elements that are in either set, but not in both:

swift
let symmetricDifference = setA.symmetricDifference(setB)
print(symmetricDifference) // Output: [1, 2, 5, 6] (order may vary)

Set Comparisons

You can compare sets to check subset, superset, and equality relationships:

swift
let group1: Set = [1, 2, 3]
let group2: Set = [1, 2, 3, 4, 5]
let group3: Set = [1, 2, 3]

// Check if group1 is a subset of group2
print(group1.isSubset(of: group2)) // Output: true

// Check if group2 is a superset of group1
print(group2.isSuperset(of: group1)) // Output: true

// Check if group1 is equal to group3
print(group1 == group3) // Output: true

// Check if group1 and group2 have no elements in common
print(group1.isDisjoint(with: group2)) // Output: false

Real-world Applications of Sets

Filtering Duplicate Values

Sets are excellent for removing duplicates from a collection:

swift
let userSubmittedTags = ["swift", "ios", "swift", "programming", "mobile", "ios", "swift"]
let uniqueTags = Set(userSubmittedTags)
print(uniqueTags)
// Output: ["programming", "mobile", "swift", "ios"] (order may vary)

// If you need an array back with no duplicates:
let uniqueTagsArray = Array(uniqueTags)

Membership Testing

Sets offer efficient lookup performance compared to arrays:

swift
let allowedUsers: Set = ["user1", "user2", "admin1", "admin2"]

func checkAccess(for username: String) -> Bool {
return allowedUsers.contains(username)
}

print(checkAccess(for: "user1")) // Output: true
print(checkAccess(for: "guest")) // Output: false

Finding Common Elements

swift
let aliceInterests: Set = ["reading", "hiking", "cooking", "photography"]
let bobInterests: Set = ["gaming", "hiking", "swimming", "photography"]

let commonInterests = aliceInterests.intersection(bobInterests)
print("Alice and Bob both enjoy: \(commonInterests)")
// Output: Alice and Bob both enjoy: ["photography", "hiking"] (order may vary)

let uniqueToAlice = aliceInterests.subtracting(bobInterests)
print("Interests unique to Alice: \(uniqueToAlice)")
// Output: Interests unique to Alice: ["cooking", "reading"] (order may vary)

Tracking Visited Items

swift
var visitedPages = Set<String>()

// User navigates through pages
func visitPage(_ page: String) {
if !visitedPages.contains(page) {
print("New page visited: \(page)")
visitedPages.insert(page)
} else {
print("Page already visited: \(page)")
}
}

visitPage("/home") // Output: New page visited: /home
visitPage("/products") // Output: New page visited: /products
visitPage("/about") // Output: New page visited: /about
visitPage("/home") // Output: Page already visited: /home

Summary

Sets are a powerful collection type in Swift that provide:

  • Unordered collections of unique values
  • Fast membership testing with the contains method
  • Built-in mathematical set operations (union, intersection, etc.)
  • Efficient comparison operations for subset and superset relationships

When should you use Sets?

  • When element order doesn't matter
  • When you need to ensure uniqueness of elements
  • When you need to perform set operations
  • When you need efficient membership testing

Practice Exercises

  1. Create a function that takes two arrays and returns an array containing only the common elements (without duplicates).

  2. Create a program that manages a shopping list using a Set. Implement functions to add items, remove items, and check if an item is already on the list.

  3. Write a program for a library that tracks which books are available and which are checked out. Use sets to represent the collection of all books and the subset of checked-out books.

  4. Implement a spell checker that uses a Set to store a dictionary of valid words, then checks if words from an input text are spelled correctly.

Additional Resources

Happy coding with Swift Sets!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)