Contents

Swift Sets

Sets

A set is a collection of unique elements. By unique, we mean no two elements in a set can be equal. Unlike sets in C++, elements of a set in Swift are not arranged in any particular order. Internally, a set in Swift uses a hash table to store elements. For instance, consider the task of finding the number of unique marks scored by students in a class. Let a list of marks be:
list = [98, 80, 86, 80, 98, 98, 67, 90, 67, 84].
In this list:

  • 98 occurs three times,
  • 80 and 67 occur twice,
  • 84, 86, and 90 occur only once.
Creating Sets

You can create an empty set using the following syntax, explicitly specifying the data type of the set:

Syntax:

				
					var mySet = Set<data_type>()

				
			

Here, data_type is the type of data the set will store, such as Int, Character, String, etc.

Example: Creating Empty Sets

				
					// Swift program to create empty sets and add elements
import Foundation

// Creating an empty set of Int data type 
var mySet1 = Set<Int>()
mySet1.insert(5)
mySet1.insert(15)
mySet1.insert(5)
print("mySet1:", mySet1)

// Creating an empty set of String data type 
var mySet2 = Set<String>()
mySet2.insert("Apple")
mySet2.insert("Banana")
print("mySet2:", mySet2)

// Creating an empty set of Character data type 
var mySet3 = Set<Character>()
mySet3.insert("A")
mySet3.insert("B")
print("mySet3:", mySet3)

// Creating an empty set of Boolean data type 
var mySet4 = Set<Bool>()
mySet4.insert(true)
mySet4.insert(false)
print("mySet4:", mySet4)

				
			

Output:

				
					mySet1: [15, 5]  
mySet2: ["Apple", "Banana"]  
mySet3: ["B", "A"]  
mySet4: [true, false]

				
			
Initialization of Sets

Method 1: Implicitly determined data type: You can initialize a set without explicitly specifying its data type.

Syntax:

				
					var mySet: Set = [value1, value2, value3, …]

				
			

Example:

				
					var mySet1: Set = [10, 20, 30, 40]
var mySet2: Set = ["Red", "Blue", "Green"]
var mySet3: Set = ["A", "B", "C"]

print("mySet1:", mySet1)
print("mySet2:", mySet2)
print("mySet3:", mySet3)

				
			

Output:

				
					mySet1: [10, 30, 40, 20]  
mySet2: ["Green", "Blue", "Red"]  
mySet3: ["B", "A", "C"]

				
			

Method 2: Explicitly specifying data type: You can initialize a set and explicitly define its data type:

Syntax:

				
					var mySet: Set<data_type> = [value1, value2, value3, …]

				
			

Example: Explicit Initialization

				
					var mySet1: Set<Int> = [1, 2, 3, 4, 5]
var mySet2: Set<String> = ["Dog", "Cat", "Bird"]
var mySet3: Set<Character> = ["X", "Y", "Z"]

print("mySet1 elements are:")
for element in mySet1 {
    print(element)
}

print("\nmySet2 elements are:")
for element in mySet2 {
    print(element)
}

print("\nmySet3 elements are:")
for element in mySet3 {
    print(element)
}

				
			

Output:

				
					mySet1 elements are:  
1  
2  
3  
4  
5  

mySet2 elements are:  
Bird  
Cat  
Dog  

mySet3 elements are:  
X  
Y  
Z  

				
			

Method 3: Using insert()The insert() method allows you to add elements to a set.

Syntax:

				
					mySet.insert(value)

				
			
				
					Example: Adding Elements Using insert()
swift
Copy code

				
			

Output:

				
					Elements of mySet are:  
Phone  
Laptop  
Tablet  

				
			
Iterating Over a Set

1. Using for-in Loop: Directly access each element in a set.

				
					myArray.append("iPad")
print("myArray:", myArray)

				
			

Output:

				
					// Output
mySet1 elements are :
15
21
1
4
13
6

mySet2 elements are :
Kunal
Honey
Bhuwanesh
Aarush
Nawal

				
			

2. Using index(_:offsetBy:)Access elements by their index, useful for specific ordering.

				
					var index = 0
while index < mySet.count {
    print(mySet[mySet.index(mySet.startIndex, offsetBy: index)])
    index += 1
}

				
			

Output:

				
					// Output
mySet1 elements: 
10
4
9
3
8

mySet2 elements: 
3.123
1.123
9.123
4.123
8.123

				
			
Comparing Sets

1. Custom Comparison (contains() method): Iterate and compare each element between two sets for equality

				
					func Compare(mySet1: Set<Int>, mySet2: Set<Int>) -> Bool {
    return mySet1.allSatisfy { mySet2.contains($0) } &&
           mySet2.allSatisfy { mySet1.contains($0) }
}

				
			

Output:

				
					// Output
Are myset1 and myset2 equal ? false
Are myset1 and myset3 equal ? false
Are myset2 and myset3 equal ? true

				
			

2. Using == Operator: Directly compare sets for equality.

				
					let areEqual = mySet1 == mySet2

				
			

Output:

				
					// Output
Are myset1 and myset2 equal ? true
Are myset1 and myset3 equal ? false
Are myset2 and myset2 equal ? false

				
			
Set Operations

1. Union:Combine elements of two sets.

				
					var myArray: [String] = ["Swift", "Xcode", "iOS", "iPad"]
myArray.remove(at: 2)
print("myArray after removal:", myArray)

				
			

Output:

				
					// Output
Union set: [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 35, 40, 45, 50]

				
			

2. Intersection: Find common elements.

				
					let intersectionSet = mySet1.intersection(mySet2)

				
			

Output:

				
					// Output
Intersection set: [15, 30]

				
			

3. Subtraction: Elements in one set but not the other.

				
					let subtractionSet = mySet1.subtracting(mySet2)

				
			

Output:

				
					// Output
Subtraction set: [3, 6, 9, 12, 18, 21, 24, 27]

				
			

4. Symmetric Difference: Elements unique to each set.

				
					let symmetricDifferenceSet = mySet1.symmetricDifference(mySet2)

				
			

Output:

				
					// Output
Symmetric difference set: [3, 5, 6, 9, 10, 12, 18, 20, 21, 24, 25, 27, 35, 40, 45, 50]

				
			

5. Subset Check:Determine if one set is a subset of another.

				
					let isSubset = mySet1.isSubset(of: mySet2)

				
			

Output: 

				
					// Output
Is mySet1 a subset of mySet2 ?: false

				
			
Modifying Sets

1. Adding Elements:

				
					mySet.insert(newElement)

				
			

2. Removing Elements:

				
					mySet.remove(elementToRemove)

				
			

3. Clearing All Elements:

				
					mySet.removeAll()

				
			

4. Check Membership:

				
					if mySet.contains(specificElement) { /*...*/ }

				
			

How to remove first element from the Set in Swift?

Swift Set and the removeFirst() Function

A set in Swift is a generic collection that stores unordered values of the same type. It ensures all elements are unique, meaning no duplicates are allowed. Sets are particularly useful when the order of values doesn’t matter, and only uniqueness is required. Internally, a set uses a hash table for storing its elements.

Sets can be mutable (modifiable) or immutable (fixed). To remove the first element from a set, you can use the removeFirst() method. Since sets are unordered, this method removes and returns a random element from the set.

Syntax:

				
					setName.removeFirst()

				
			

Example:

				
					// Swift program to remove an element from a set
import Swift

// Creating a set of numbers
var numbers: Set = [12, 45, 78, 23, 56, 89]

// Displaying the original set
print("Original Set:", numbers)

// Removing the first element
let removedElement = numbers.removeFirst()

// Displaying the removed element
print("Removed Element:", removedElement)

// Displaying the set after removal
print("Final Set:", numbers)

				
			

Output:

				
					Original Set: [45, 12, 78, 23, 56, 89]
Removed Element: 45
Final Set: [12, 78, 23, 56, 89]

				
			

Swift Set and the removeAll() Function

A set in Swift is a generic, unordered collection used to store values of the same type. You cannot mix data types within a set—for example, a string set can only store string values, not integers. Sets are particularly useful when the order of elements is irrelevant and only unique values are required. Internally, sets rely on a hash table for efficient storage.

Sets can be mutable (modifiable) or immutable (fixed). To remove all elements from a set, you can use the removeAll() method. This method clears the set entirely, leaving it empty.

Syntax:

				
					setName.removeAll()

				
			

Example:

				
					// Swift program to remove all elements from a set
import Swift

// Creating a set of author's names
var authorNames: Set = ["Alice", "Bob", "Charlie", "Diana", "Eve"]

// Displaying the original set
print("Original Set:", authorNames)

// Removing all elements
authorNames.removeAll()

// Displaying the set after removal
print("Final Set:", authorNames)

				
			

Output:

				
					Original Set: ["Diana", "Eve", "Alice", "Charlie", "Bob"]
Final Set: []

				
			

How to check if the set contains a given element in Swift?

Swift supports generic collections, and sets are one of them. A set is used to store unordered values of the same type. For instance, if a set is of integer type, it can only store integer values, not strings or other types. Sets are preferred over arrays when the order of values is irrelevant or when you need to store unique values only. Sets do not allow duplicate elements and use a hash table for storage.

In Swift, you can easily check if a set contains a specific element using the contains() function. This function is case-sensitive; for example, "Mohan" and "mohan" are considered different values.

Syntax:

				
					setName.contains(element)

				
			
				
					// Swift program to check if a specified element is present in the set
import Swift

// Creating a set of ranks
var ranks: Set = [10, 20, 30, 40, 50, 60]

// Checking if a specific element is present in the set
if ranks.contains(15) {
    print("15 is present in the set")
} else {
    print("15 is not present in the set")
}

// Checking for another element in the set
if ranks.contains(40) {
    print("40 is present in the set")
} else {
    print("40 is not present in the set")
}

				
			

Output:

				
					15 is not present in the set
40 is present in the set

				
			

How to count the elements of a Set in Swift?

Swift provides various types of generic collections, with set being one of them. A set is a collection used to store unordered values of the same type. Unlike arrays, sets do not allow duplicate values, ensuring that all elements are unique. Internally, sets use a hash table for storing elements efficiently.

To determine the number of elements in a set, you can use the count property. This property returns the total number of values in the set.

Syntax:

				
					setName.count

				
			

Example:

				
					// Swift program to find the total number of elements in a set
import Swift

// Creating a set of employee salaries
var employeeSalaries: Set = [45000, 28000, 36000, 52000, 60000, 72000]

// Counting the total number of elements
let totalCount1 = employeeSalaries.count

// Displaying the result
print("Total number of elements in the set:", totalCount1)

// Creating an empty set of integers
var emptySet = Set<Int>()

// Counting the total number of elements in the empty set
let totalCount2 = emptySet.count

// Displaying the result
print("Total number of elements in the empty set:", totalCount2)

				
			

Output:

				
					Total number of elements in the set: 6
Total number of elements in the empty set: 0

				
			

Sorting a Set in Swift

In Swift, a set is a generic collection used to store unordered unique values of the same type. Sets are useful when the order of elements is irrelevant or when duplicates need to be avoided. Internally, they use a hash table for storage.

You can sort the elements of a set using the sorted() function. By default, this function sorts the elements in ascending order. However, you can sort them in descending order by passing the greater-than operator (>). Similarly, the less-than operator (<) explicitly sorts elements in ascending order.

Syntax:

				
					setName.sorted(by: operatorValue)

				
			

Example:

				
					// Swift program to sort the elements of a set
import Swift

// Creating a set of employee names
var employeeNames: Set = ["Amit", "Pooja", "Raj", "Meera", "Vikas"]

print("Employee names before sorting:", employeeNames)

// Sorting the elements of the set
let sortedNames = employeeNames.sorted()

// Displaying the sorted result
print("Employee names after sorting:", sortedNames)

				
			

Output:

				
					Employee names before sorting: ["Raj", "Amit", "Meera", "Pooja", "Vikas"]
Employee names after sorting: ["Amit", "Meera", "Pooja", "Raj", "Vikas"]

				
			

How to check if a set is empty in Swift?

Swift provides a built-in property isEmpty to check if a set contains elements or not. A set in Swift is used to store unordered, unique values of the same type. When isEmpty is called, it returns true if the set contains no elements and false otherwise.

Syntax:

				
					arrayName.removeFirst(x: Int)
asetName.isEmpty

				
			

Example :

				
					// Swift program to check if the given set is empty or not
import Swift

// Creating a set of employee salaries
var employeeSalaries: Set = [30000, 12200, 14000, 67800, 10000, 90000]

// Checking if the set is empty using the isEmpty property
let isEmployeeSalariesEmpty = employeeSalaries.isEmpty

// Displaying the result
print("Is the employeeSalaries set empty?", isEmployeeSalariesEmpty)

// Creating an empty set of integer type
var employees = Set<Int>()

// Checking if the set is empty using the isEmpty property
let isEmployeesEmpty = employees.isEmpty

// Displaying the result
print("Is the employees set empty?", isEmployeesEmpty)

				
			

Output:

				
					Is the employeeSalaries set empty? false
Is the employees set empty? true

				
			

How to shuffle the elements of a set in Swift?

In Swift, a set is an unordered collection used to store unique elements of the same type. Sets do not allow duplicate values and use a hash table to store elements. Sets can be mutable or immutable based on whether they are assigned to a variable or constant. Swift provides the shuffled() function to shuffle the elements in a set, returning a new set with the elements in random order.

Syntax:

				
					setName.shuffled()

				
			

Example:

				
					// Swift program to shuffle all the elements from the set
import Swift

// Creating a set of author ratings
var authorRatings: Set = [2, 458, 65, 8, 76, 4, 982, 3, 4, 5]

// Displaying the original set
print("Original Set:", authorRatings)

// Shuffle all the elements of the set using the shuffled() function
let shuffledRatings = authorRatings.shuffled()

// Displaying the shuffled elements
print("Shuffled elements:", shuffledRatings)

				
			

Output:

				
					Original Set: [458, 76, 982, 8, 5, 4, 3, 65, 2]
Shuffled elements: [65, 5, 4, 982, 76, 8, 2, 3, 458]

				
			

Difference Between Sets and Arrays

An array is a linear data structure used to store multiple elements in a single variable. These elements are stored in contiguous memory, and each element can be accessed using an index. Arrays can store elements of the same type.

Syntax:

				
					var arr: [DataType] = [value1, value2, value3, ..., valueN]

				
			

Example:

				
					// Swift program to illustrate array

// Creating and initializing an Array with Integer Values
var arr: [Int] = [1, 2, 3, 4, 5]

// Display the array
print(arr)

				
			

Output:

				
					[1, 2, 3, 4, 5]

				
			

Set in Swift

A set is a data structure that stores unique elements, meaning no duplicate values are allowed. Unlike arrays, sets automatically eliminate duplicate elements. Sets also support operations like union, intersection, and

				
					// Swift program to illustrate set

// Creating and initializing set of Integer Values
var set1: Set = [1, 2, 2, 2, 3, 4]

// Creating and initializing set of String Values
var set2: Set = ["Apple", "Banana", "Orange", "Banana", "Apple"]

// Display the result
print(set1)
print(set2)

				
			

Output:

				
					[3, 4, 1, 2]
["Orange", "Banana", "Apple"]

				
			
ArraySet
Arrays can have elements of any type, but their elements must be ordered.Sets store unique elements of the same type but have no specific order.
Arrays support both mutable and immutable versions, but they preserve the order of elements when modified.Sets support only unique elements, and adding or removing elements does not affect order since sets are unordered.
Arrays have a fixed size once initialized.Sets can dynamically grow or shrink as elements are added or removed, with no concern for order.
You can access elements in an array through indexing (e.g., array[0]).You cannot access elements directly by index in a set; you can only iterate over them.
Arrays use more memory compared to sets as they store duplicates and maintain order.Sets use less memory because they store only unique elements.