Understanding Swift - Sets


Understanding Sets in Swift

A Set in Swift is an unordered collection that holds unique values of the same type. Unlike arrays, sets do not maintain a specific order but offer fast retrieval using a hash table.


Key Characteristics:

  • Distinct values: No duplicates allowed.
  • Unordered storage: No fixed sequence.
  • Fast operations: Due to hashing.
  • Strict type checking: Ensures data integrity.


Mutability in Sets

Mutable Sets (var): Allow adding and removing elements.

Immutable Sets (let): Once initialized, elements cannot be changed.

var dynamicSet: Set<String> = ["Swift", "Python", "Java"]
dynamicSet.insert("C++") // Allowed

let fixedSet: Set<String> = ["Red", "Blue", "Green"]
// fixedSet.insert("Yellow") // ❌ Error: Cannot modify a constant set

Creating Sets in Swift

There are multiple ways to initialize a set in Swift.

1. Using Set() Constructor


To create an empty set, specify its type explicitly:

var emptySet = Set<String>() // Creates an empty set of type String



2. Using an Array Literal

A more common approach is using an array literal to initialize a set:

var fruits: Set = ["Apple", "Banana", "Cherry"]

Adding Elements to a Set

The insert() method adds new items to a set.

var colors = Set<String>()
colors.insert("Red")
colors.insert("Blue")
colors.insert("Green")
colors.insert("Yellow")
print ("Colors Set:", colors)

Output:

Colors Set: ["Blue", "Red", "Yellow", "Green"]

Removing Elements from a Set

The remove() method eliminates an element from a set.

var numbers: Set = [10, 20, 30, 40, 50]
numbers.remove(30)
print("Updated Numbers Set:", numbers)

Output:

Updated Numbers Set: [10, 50, 20, 40]

Checking Element Existence in a Set

The contains() method verifies whether a specific value exists in a set.

var languages: Set = ["Swift", "Kotlin", "Dart"]
if languages.contains("Swift") {
print("Swift is in the set!")
} else {
print("Swift is not in the set.")
}

Output:

Swift is in the set!

Displaying Elements in a Set

You can loop through a set using a for loop.

var animals: Set = ["Dog", "Cat", "Elephant"]
for animal in animals {
print(animal)
}

Output:

Elephant
Cat
Dog

Iterating Over a Set in Swift

Iterating over a set in Swift allows developers to access and process individual elements efficiently. Since sets are unordered collections, iterating over them provides a practical way to work with their contents. In Swift, you can iterate over a set using various methods, such as the for-in loop, enumerated() function, and the forEach() function. Let's explore these methods in detail with examples.

1. Using the For-In Loop

The simplest and most common way to iterate over a set is by using a for-in loop. This method sequentially accesses each element in the set, making it easy to perform operations on them.


import Foundation

var mySet1: Set = [10, 25, 42, 7]

var numberDescriptions: [Int: String] = [
10: "Ten is a base number.",
25: "Twenty-five is a square number.",
42: "Forty-two is the answer to life, the universe, and everything.",
7: "Seven is considered a lucky number."
]

print("Elements of Set:")
for number in mySet1 {
print(" \(number) : \(numberDescriptions[number] ?? "No description available" ) ")
}

Output

Elements of Set:
42: Forty-two is the answer to life, the universe, and everything.
7: Seven is considered a lucky number.
25: Twenty-five is a square number.
10: Ten is a base number.

2. Using the enumerated() Function

The enumerated() function allows you to retrieve both the index and value while iterating over a set. This can be useful for tracking the position of elements, even though sets do not maintain a specific order.


import Foundation

var mySet2: Set = [12, 33, 27, 19]

var numberTypes: [Int: String] = [
12: "Even number",
33: "Odd number",
27: "Multiple of three",
19: "Prime number"
]

print("Elements of Set:")
for (index, value) in mySet2.enumerated() {
print(" \(value) is at index \(index) and is categorized as: \(numberTypes[value] ?? "Unknown" ) ")
}

Output

Elements of Set:
33 is at index 0 and is categorized as: Odd number
12 is at index 1 and is categorized as: Even number
19 is at index 2 and is categorized as: Prime number
27 is at index 3 and is categorized as: Multiple of three

3. Using the forEach() Function

Swift provides the forEach() function, which is a more concise way to iterate over a set. It allows inline closures for performing actions on each element without manually iterating.


import Foundation

var mySet3: Set = [5, 14, 30, 21]

var numberFacts: [Int: String] = [
5: "Five is the number of fingers on a hand.",
14: "Fourteen is the atomic number of silicon.",
30: "Thirty is the minimum age for a U.S. senator.",
21: "Twenty-one is the legal drinking age in many countries."
]

print("Elements of Set:")
mySet3.forEach { number in
print(" \(number): \(numberFacts[number] ?? "No fact available") ")
}

Output

Elements of Set:
21: Twenty-one is the legal drinking age in many countries.
5: Five is the number of fingers on a hand.
14: Fourteen is the atomic number of silicon.
30: Thirty is the minimum age for a U.S. senator.

Set Operations in Swift: A Comprehensive Guide

Swift provides powerful built-in set operations that allow developers to combine, compare, and manipulate sets efficiently. These operations help in handling unique collections of elements effectively.


Types of Set Operations

Swift supports five key set operations:

  • Union: Combines two sets into one without duplicates.
  • Intersection: Extracts common elements from two sets.
  • Subtraction: Removes elements from one set that are present in another.
  • Difference (Symmetric Difference): Finds elements present in either set but not in both.
  • Subset: Checks if all elements of one set exist in another.


1. Union

The union operation merges two sets, ensuring all unique elements are included.


Syntax:

Set1.union(Set2)


Example:

import Foundation

var numbers1: Set = [1, 2, 3, 4]
var numbers2: Set = [3, 4, 5, 6]

var infoDict: [String: Any] = ["First Set": numbers1, "Second Set": numbers2]

let result = numbers1.union(numbers2)
infoDict["Union Result"] = result

print("Set Details: \(infoDict)")

Output:

Set Details: ["First Set": [1, 2, 3, 4], "Second Set": [3, 4, 5, 6], "Union Result": [1, 2, 3, 4, 5, 6]]

2. Intersection

The intersection operation finds elements common in both sets.


Syntax:

Set1.intersection(Set2)

Example:

import Foundation

var setA: Set = [10, 20, 30, 40]
var setB: Set = [30, 40, 50, 60]

var detailsDict: [String: Any] = ["Set A": setA, "Set B": setB]

let commonElements = setA.intersection(setB)
detailsDict["Intersection Result"] = commonElements

print("Set Information: \(detailsDict)")

Output:

Set Information: ["Set A": [10, 20, 30, 40], "Set B": [30, 40, 50, 60], "Intersection Result": [30, 40]]

3. Subtraction

The subtracting operation removes elements from the first set that exist in the second.

Syntax:

Set1.subtracting(Set2)

Example:

import Foundation

var fruits1: Set = ["Apple", "Banana", "Cherry"]
var fruits2: Set = ["Banana", "Cherry", "Date"]

var fruitDict: [String: Any] = ["Set 1": fruits1, "Set 2": fruits2]

let uniqueFruits = fruits1.subtracting(fruits2)
fruitDict["Subtraction Result"] = uniqueFruits

print("Fruit Details: \(fruitDict)")

Output:

Fruit Details: ["Set 1": ["Apple", "Banana", "Cherry"], "Set 2": ["Banana", "Cherry", "Date"], "Subtraction Result": ["Apple"]]

4. Difference (Symmetric Difference)

The symmetricDifference operation finds elements that are unique to each set.

Syntax:

Set1.symmetricDifference(Set2)

Example:

import Foundation

var cities1: Set = ["New York", "London", "Paris"]
var cities2: Set = ["Paris", "Tokyo", "Sydney"]

var cityDict: [String: Any] = ["Cities Set 1": cities1, "Cities Set 2": cities2]

let uniqueCities = cities1.symmetricDifference(cities2)
cityDict["Difference Result"] = uniqueCities

print("City Details: \(cityDict)")

Output:

City Details: ["Cities Set 1": ["New York", "London", "Paris"], "Cities Set 2": ["Paris", "Tokyo", "Sydney"], "Difference Result": ["New York", "London", "Tokyo", "Sydney"]]

5. Subset

A subset is when all elements of the first set exist in the second.

Syntax:

Set1.isSubset(of: Set2)

Example:

import Foundation

var smallSet: Set = [2, 4]
var largeSet: Set = [1, 2, 3, 4, 5, 6]

var subsetDict: [String: Any] = ["Small Set": smallSet, "Large Set": largeSet]

let isSubset = smallSet.isSubset(of: largeSet)
subsetDict["Is Subset?"] = isSubset

print("Subset Details: \(subsetDict)")

Output:

Subset Details: ["Small Set": [2, 4], "Large Set": [1, 2, 3, 4, 5, 6], "Is Subset?": true]