Swift Sets: In this tutorial, you will learn about sets, creating sets, modifying them and some common activities in sets.

In the previous Swift Arrays tutorial, we learned about creating array that can hold different values in an arranged rundown.

However, on the off chance that we need to ensure a rundown can hold a worth just a single time, we use a set in Swift.

What is Swift Sets?

Swift set is a straightforward container which can hold numerous values of a data type in an unordered list. It can’t store same value twice. Here, the unordered list means you will not get the items in a similar way where you have enter in the set.

Sets is essentially a container that can hold numerous worth of data type in an unordered rundown and guarantees unique element in the container (i.e each data shows up just a single time).

Unordered rundown means you will not get the elements in a similar order as you defined the item in the Set.

The fundamental benefit of using Sets over arrays is the point at which you need to ensure that an item possibly shows up once and when the order for items isn’t significant.

values put away in a set should be hashable. This means it needs to give a hashValue property. This is significant on the grounds that sets are unordered and it uses hashValue is used to access to the elements of the sets.

The entirety of Swift’s fundamental types (like String, Int, Double, and Bool) are hashable by default, and can be used as set worth sorts. Notwithstanding, you can likewise create your Hashable Type in Swift that can be put away in a set.


How to declare a set in Swift?

You can create an unfilled set by indicating the sort as Set followed by the type of Data it can store inside < >.

Example1: Declaring an empty set

let emptyIntSet:Set = []
print(emptyIntSet)

OR

let emptyIntSet:Set = Set()
print(emptyIntSet)

At the point when you run the program, the output will be:

[ ]

In the above program, we have declared a consistent emptyIntSet of type Set that can store various values of number and introduced with 0 qualities.

Since, Swift is a sort inference language, you can likewise make set straightforwardly without indicating the Data Type however should introduce for certain qualities so compiler can infer its sort as:

Example 2: Declaring a set with some values

let someIntSet:Set = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(someIntSet)

At the point when you run the program, the output will be:

[2, 4, 9, 5, 6, 7, 3, 1, 8]

In the above program, we have declared a consistent someIntSet that can store sets of Integer without indicating the sort unequivocally. Notwithstanding, we need to write :Set when defining the variable, in any case Swift will create an array for us.

Likewise, as arrays, we have introduced the set with 1, 2 ,3 ,4, 5, 6, 7, 8, 9 values using the [] brackets.

As you’ve realized, when you attempt to print the values inside the set as print(someIntSet), you will get the outcomes in a a different order than to you have defined the items in the set since it stores value with no defined requesting. Consequently, each time when you access the order changes.

Example 3: Declaring a set with duplicate values
let someStrSet:Set = ["ab","bc","cd","de","ab"]
print(someStrSet)

At the point when you run the program, the output will be:

["de", "ab", "cd", "bc"]

In the above program, we have defined a copy value abin the set. Furthermore, at the point when we attempt to get to the worth inside the set using print(someStrSet), the copy value is automatically eliminated from the set. Subsequently, set ensures unique elements/values inside it.

You can likewise declare a set with your own custom Hashable sort in Swift. To learn more visit, visit Swift Hashable.


How to access set elements in Swift?

You can’t get to elements of a set using subscript syntax as arrays. This is on the grounds that sets are unordered and don’t have indices to get to the elements.

Thus, you need to get to the set using its techniques and properties or using for-in loops.

Example 4: Accessing elements of a set

var someStrSet:Set = ["ab", "bc", "cd", "de"]
for val in someStrSet {
    print(val)
}

At the point when you run the program, the output will be:

de
ab
cd
bc

In the above program, we get the val in different order in comparison to elements of a set since sets are unordered unlike arrays.

You can likewise get to element of a set straightforwardly eliminating the worth from the set as beneath:


Example 5: Accessing elements of a set using remove()
var someStrSet:Set = ["ab", "bc", "cd", "de"]
let someVal = someStrSet.remove("cd")
print(someVal)
print(someStrSet)

At the point when you run the program, the output will be:

Optional("cd")
["de", "ab", "bc"]

In the above program, you can see the eliminate technique returns an optional string. Thusly, it’s prescribed you to do optional taking care of as beneath. To learn more about optionals, visit Swift Optionals.


Example 6: Optional handling for remove()
var someStrSet:Set = ["ab", "bc", "cd", "de"]
if let someVal = someStrSet.remove("cd") {
    print(someVal)
    print(someStrSet)
} else {
    print("cannot find element to remove")
}

At the point when you run the program, the output will be:

cd
["de", "ab", "bc"]

How to add new element in a set?

You can add another element to a set using insert() method in Swift.

Example 7: Add new element using insert()
var someStrSet:Set = ["ab", "bc", "cd", "de"]
someStrSet.insert("ef")
print(someStrSet)

At the point when you run the program, the output will be:

["ab", "de", "cd", "ef", "bc"]

In the above program, we used the set’s insert() strategy to add another element to a set. Since, sets are unordered, the situation of the inserted element isn’t known.


Set Operations

Another main benefit of using Sets is you can perform set activities, for example, combining two sets together, determining out which values two sets have in common and so forth This tasks are like the Set activity in Mathematics.


1. Union

The union of two sets an and b is the arrangement of elements which are in a, or b, or in both an and b.

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 2, 4, 6, 8]
print(a.union(b))

At the point when you run the above program, the output will be:

[8, 2, 9, 4, 5, 7, 6, 3, 1, 0]

2. Intersection

The intersection point of two sets an and b is the set that contains all elements of a that likewise have a place with b.

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 3, 7, 6, 8]
print(a.intersection(b))

At the point when you run the above program, the output will be:

[7, 3]

In this manner, print(a.intersection(b)) outputs another set with values [7, 3] that are basic in both an and b.


3. Subtracting

The subtraction of two sets an and b is the set that contains all elements of a however eliminating the elements that likewise have a place with b.

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 3, 7, 6, 8]
print(a.subtracting(b))

At the point when you run the above program, the output will be:

[5, 9, 1]

Accordingly, print(a.subtracting(b)) outputs a new set with values [5, 9, 1].


4. Symmetric Difference

The symmetric difference of two sets a and b is the set that contains all elements which are in both of the sets yet not in the two of them.

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 3, 7, 6, 8]
print(a.symmetricDifference(b))

At the point when you run the above program, the output will be:

[5, 6, 8, 0, 1, 9]

In this way, print(a.symmetricDifference(b)) outputs another set with values [5, 6, 8, 0, 1, 9].


Set Membership and Equality Operations

Set Equality

You can use== operator to check if two sets contains same elements or not. It returns true if two sets contains same elements in any case returns false.

Example 5: Set equality operations

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 3, 7, 6, 8]
let c:Set = [9, 7, 3, 1, 5]

if a == b {
    print("a and b are same")
} else {
    print("a and b are different")
}

if a == c {
    print("a and c are same")
} else {
    print("a and c are different")
}

At the point when you run the above program, the output will be:

a and b are different
a and c are same

Set membership

You can likewise check connection between two sets using the accompanying strategies:

  • isSubset(of:)This technique decides if the entirety of the upsides of a set are contained in the predetermined set.
  • isSuperset(of:) This technique decides if a set contains the entirety of the values in a predefined set
  • isStrictSubset(of:) or isStrictSuperset(of:): This technique decides if a set is a subset or superset, but not equivalent to, a predetermined set.
  • isDisjoint(with:) This technique decides if two sets have no values in common.

Example 6: Set membership operations

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 3, 1, 7, 6, 8, 9, 5]

print("isSubset:", a.isSubset(of: b))
print("isSuperset:", b.isSuperset(of: a))
print("isStrictSubset:", a.isStrictSubset(of: b))
print("isDisjointWith:", a.isDisjoint(with: b))

At the point when you run the above program,the output will be:

isSubset: true
isSuperset: true
isStrictSubset: true
isDisjointWith: false

Let’s analyze methods used inside the print statement below:

  • isSubset returns true because the set b contains all the elements in a
  • isSuperset return true because b contains the entirety of the values of a.
  • isStrictSubset returns true on the grounds that set b contains all the element in a and the two sets are not equivalent.
  • isDisjointWith returns false on the grounds that have some values in common.

Some helpful built in Set functions & properties

1. isEmpty

This property decides whether a set is unfilled or not. It returns true if a set doesn’t contain any worth in any case returns false.

Example 7: How isEmpty works?

let intSet:Set = [21, 34, 54, 12]
print(intSet.isEmpty)

At the point when you run the program, the output will be:

false

2. first

This property is used to get to first element of a set.

Example 8: How first works?

let intSet = [21, 34, 54, 12]
print(intSet.first)

At the point when you run the program, the output will be:

Optional(54)

Since set is an unordered assortment, the first property doesn’t ensure the first element of the set. You may get other worth than 54.

Likewise, you can use last property to get to last element of a set.


3. insert

The insert function is used to insert/append element in the set.

Example 9: How insert works?

var intSet:Set = [21, 34, 54, 12]
intSet.insert(50)
print(intSet)

At the point when you run the program, the output will be:

[54, 12, 50, 21, 34]

4. reversed

This function returns the elements of a set reverse order.

Example 10: How reversed() works?

var intSet:Set = [21, 22, 23, 24, 25]
print(intSet)
let reversedSet = intSet.reversed()
print(reversedSet)

At the point when you run the program, the output will be:

[22, 23, 21, 24, 25]
[25, 24, 21, 23, 22]

5. count

This property returns the total number of elements in a set.

Example 11: How count works?

let floatSet:Set = [10.2, 21.3, 32.0, 41.3]
print(floatSet.count)

At the point when you run the program, the output will be:

4

6. removeFirst

This function eliminates and returns the first worth from the set.

Example 12: How removeFirst works?

var strSet:Set = ["ab", "bc", "cd", "de"]
let removedVal = strSet.removeFirst()
print("removed value is \(removedVal)")
print(strSet)

At the point when you run the program, the output will be:

removed value is de
["ab", "cd", "bc"]

Likewise, you can likewise use removeAll function to empty a set.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.