EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Swift

Swift Sets

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,
  • 8486, 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 IntCharacterString, 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) { /*...*/ }
End of lesson.