Swift - Sets



Swift sets are used to store distinct values of the same types but they don’t have definite ordering as arrays have. It runs a strict type checking which means you are not allowed to enter a wrong type in an array, even by mistake.

If you assign a created set to a variable, then it is always mutable, which means you can change it by adding, removing, or changing its elements. But if you assign a set to a constant, then that set is immutable, which means you cannot able to add new elements to that set.

If you try to do so, the compiler will throw an error. The Set uses a hash table to store elements. All the basic swift values are of hashable type by default and may be used as set values.

Creating Sets in Swift

To create an empty set of a certain type we can use the Set() initializer. It explicitly accepts the data type. A set can store the value of any data type like float, integer, string, character and double.

var someSet = Set<DataType>()

We can also create an empty set using the array literal. It is the shorthand representation of a set.

var someSet : Set<DataType> = [value]
Or
var someSet : Set = [value]

Initializing Sets in Swift

We can initialize the set using the following methods −

Using insert() method

It is a pre-defined function to add new elements to the set. It adds one element at a time.

Syntax

Following is the syntax for insert() function −

set.insert(x)

Example

import Foundation

// Initialize an empty set of String
var mySet = Set<String>()

// Inserting elements into the set using insert() function
mySet.insert("Swift")
mySet.insert("C++")
mySet.insert("C")
mySet.insert("Java")

// Displaying set
print(mySet)
Output

It will produce the following output −

["Java", "C", "Swift", "C++"]

Using array literal

We can also initialize a set using array literal. It is the easiest way to initialize a set. Also using this method, we can initialize a set with multiple values.

Syntax

Following is the syntax for array literal −

var someSet : Set = [value1, value2, value3]

Example

import Foundation

// Initialize a set of integers using an array literal
var mySet1 : Set = [3, 55, 6, 22]

var mySet2 : Set<String> = ["Swift", "Java", "C", "C++"]

// Displaying set
print("Set 1:", mySet1)
print("Set 2:", mySet2)
Output

It will produce the following output −

Set 1: [3, 6, 55, 22]
Set 2: ["C++", "Swift", "C", "Java"]

Iterating over a Set in Swift

Iterating over a set allows the developer to access and process individual elements of the given set. In Swift, we can iterate over a set using the following methods −

Using for-in loop

We can use a for-in loop to iterate over elements of the given set. It is the easiest and cleanest way to access and process each element of the given set sequentially.

Example

import Foundation

// Initialize a set of integers using an array literal
var mySet1 : Set = [3, 55, 6, 22]

print("Elements of Set:")
// Iterating through each element of the set
// Using for-in
for x in mySet1{
   print(x)
}
Output

It will produce the following output −

Elements of Set:
22
6
3
55

Using the enumerated() Function with for-in loop

If we want to fetch all the elements along with their corresponding index value then we can use the enumerated() function along with a for-in loop.

Example

import Foundation

// Initialize a set of integer type
var mySet1 : Set = [3, 55, 6, 22]

print("Elements of Set:")

// Iterating through each element of the set 
// Using for-in loop along with enumerated() function
for (index, element) in mySet1.enumerated(){
   print("\(element) is at index \(index)")
}
Output

It will produce the following output −

Elements of Set:
22 is at index 0
55 is at index 1
6 is at index 2
3 is at index 3

Using forEach() Function

Swift provides a pre-defined function named forEach() to iterate over the given set. It is useful to perform operations on the individual elements of the given set without iterating manually.

Example

import Foundation

// Initialize a set of integer type
var mySet1 : Set = [3, 55, 6, 22]

print("Elements of Set:")

// Iterating over the set using forEach() function
mySet1.forEach { num in
   print(num)
}
Output

It will produce the following output −

Elements of Set:
3
55
6
22

Set Operations in Swift

Set operations are used for combining, comparing and manipulating sets. A set supports five types of operations −

  • Union
  • Intersection
  • Subtraction
  • Difference
  • Subset

Now let us discuss them in detail.

Union

Union is used to combine the elements of two sets into a single set without duplicate elements. For example, we have two sets set1 = [2, 4, 5] and set2 = [7, 8, 9] so the union of both sets is [2, 4, 5, 8, 9]. To perform union operation on set Swift provides a pre-defined function named union(). This method returns the union of two sets.

Union

Syntax

Following is the syntax for union −

Set1.union(set2)

Example

import Foundation

// Initialize a set of integer type
var mySet1 : Set = [3, 55, 6, 22]
var mySet2 : Set = [4, 6, 21, 1]

// Union of mySet1 and mySet2
var result = mySet1.union(mySet2)

print("Resultant set: ", result)
Output

It will produce the following output −

Resultant set:  [55, 1, 3, 21, 22, 4, 6]

Intersection

Intersection is used to find only those elements that are common in both the given sets. For example, we have two sets set1 = [2, 4, 5, 1] and set2 = [7, 1, 9, 2] so the intersection of both sets is [2, 1]. To perform intersection operation on the given sets Swift provides a pre-defined function named intersection(). This method returns the intersection of two sets.

Intersection

Syntax

Following is the syntax for intersection −

Set1.intersection(set2)

Example

import Foundation

// Initialize a set of integer type
var mySet1 : Set = [3, 55, 6, 1]
var mySet2 : Set = [4, 6, 21, 1]

// Intersection of mySet1 and mySet2
var result = mySet1.intersection(mySet2)

print("Resultant set: ", result)
Output

It will produce the following output −

Resultant set:  [6, 1]

Subtraction

Subtraction is used to find only those elements that are present in set 1 but not in set 2. For example, we have two sets set1 = [2, 4, 5, 1] and set2 = [7, 1, 9, 3] so the subtraction of both sets is [2, 1, 4, 5]. To perform subtraction operation on the given sets Swift provides a pre-defined function named subtraction(). This method returns a new set containing the subtraction of two sets.

Subtraction

Syntax

Following is the syntax for subtraction −

Set1.subtracting(set2)

Example

import Foundation

// Initialize a set of integer type
var mySet1 : Set = [3, 55, 6, 1]
var mySet2 : Set = [4, 6, 21, 1]

// Subtract mySet1 from mySet2
var result = mySet2.subtracting(mySet1)

print("Resultant set: ", result)
Output

It will produce the following output −

Resultant set:  [4, 21]

Difference

Difference is used to find all the elements that are present in both the sets except the common element. For example, we have two sets set1 = [2, 4, 5, 1] and set2 = [7, 1, 9, 3] so the difference between both sets is [4, 5, 7, 9, 3]. To perform difference operation on the given sets Swift provides a pre-defined function named symmetricDifference(). This method returns a new set containing the symmetric difference of the two sets.

Difference

Syntax

Following is the syntax for difference −

Set1.symmetricDifference(set2)

Example

import Foundation

// Initialize a set of integer type
var mySet1 : Set = [3, 55, 6, 1]
var mySet2 : Set = [4, 6, 21, 1]

// Find difference between mySet1 and mySet2
var result = mySet1.symmetricDifference(mySet2)

print("Resultant set: ", result)
Output

It will produce the following output −

Resultant set:  [4, 55, 3, 21]

Subset

A set is known as the subset of another set if all the elements present in set 1 are present in set 2. For example, set1 = [2, 4, 5, 1] is the subset of set2 = [7, 9, 3, 2, 4, 5, 1]. Swift provides a pre-defined method named isSubset() to check if the given set is the subset of another set. It will return true if the given set is the subset of another set. Otherwise, it will return false.

Subset

Syntax

Following is the syntax for isSubset() −

Set1.isSubset(set2)

Example

import Foundation

// Initialize a set of integer type
var mySet1 : Set = [6, 1]
var mySet2 : Set = [4, 6, 21, 1]

// Checking whether mySet1 is the subset of mySet2
// Using isSubset() function
var result = mySet1.isSubset(of: mySet2)

print("Is mySet1 is the subset of mySet2?:", result)
Output

It will produce the following output −

Is mySet1 is the subset of mySet2?: true
Advertisements