← Back to Swift Course | Chapter 6: Collections | Lesson 3 of 7

Sets

A set is a group of unique items with no duplicates and no particular order, like a bag where you can only have one of each kind of marble.
Syntax
swift
var name: Set<Type> = [value1, value2]
name.insert(value)
name.contains(value)
setA.union(setB)
setA.intersection(setB)
setA.subtracting(setB)

Creating a Set

A Set is created either from an array literal with explicit type annotation, or with Set([...]), and automatically removes duplicate values.

Example: Creating a Set

markup
// Declare a constant `uniqueNumbers` (a `Set`), set to `[1, 2, 2, 3, 3, 3]`
let uniqueNumbers: Set = [1, 2, 2, 3, 3, 3]
// Print `uniqueNumbers.count` to the console
print(uniqueNumbers.count)
// Print `uniqueNumbers.contains(2)` to the console
print(uniqueNumbers.contains(2))

Set Operations

Sets support mathematical operations like .union(), .intersection(), and .subtracting() to combine or compare two sets.

Example: Set Operations

markup
// Declare a constant `evens` (a `Set`), set to `[2, 4, 6, 8]`
let evens: Set = [2, 4, 6, 8]
// Declare a constant `smallNumbers` (a `Set`), set to `[1, 2, 3, 4]`
let smallNumbers: Set = [1, 2, 3, 4]
// Print `evens.intersection(smallNumbers).sorted()` to the console
print(evens.intersection(smallNumbers).sorted())
// Print `evens.union(smallNumbers).sorted()` to the console
print(evens.union(smallNumbers).sorted())
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Assuming a set preserves insertion order like an array; sets are explicitly unordered.
  2. Adding a duplicate value expecting the set to grow; duplicates are automatically ignored.
  3. Using a set for a type that isn't Hashable; every element type in a Set must conform to Hashable.
Chapter Summary
  • A Set stores unique values of the same type with no defined order, written as Set<Type>.
  • Adding a duplicate value has no effect since sets automatically enforce uniqueness.
  • Sets support fast membership testing with .contains().
  • Set operations like union, intersection, and subtraction combine sets mathematically.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.