Swift Program to Iterate Over an Set


In Swift, a set is used to define a unordered collection of unique elements. To iterate over an set swift provide inbuilt forEach() function as well as for-in loop. Lets discuss both the methods in detail along with examples.

Method 1: Using for-in Loop

To iterate over an set we can use for-in loop. The for-in loop iterate through each element of the set and display them on the screen one by one.

Syntax

for x in newSet{
   print(x)
}

Where newset is the name of the set, and x variable store the current element from the newest in each iteration.

Example

In the following swift example, we will create and initialise a set of integer type. Then we use for-in loop to iterate through each element of the set and display them on the output screen.

import Foundation
import Glibc

// Creating a set of integer
var myNum : Set = [23, 56, 32, 99, 12, 27, 1] 

// Displaying set
for x in myNum{
   print(x)
}

Output

99
56
12
23
32
27
1

Method 2: Using forEach() function

We can also use forEach() function to iterate over an set. The forEach() function calls the specified closure on each element present in the given set or sequence. Its working is same as the for-in loop.

Syntax

func forEach(_myclo:)

Where myclo is the closure which takes an element of the given sequence or set as a parameter and return the result according to the statement present in the closure.

Example

In the following swift example, we will first create and initialise a set, then display the elements of the set using forEach() function. In the forEach() function, we pass a closure({myRes in print(myRes)}) which will display all the elements of the set.

import Foundation
import Glibc

// Creating a set of integer
var myFavfruit : Set = ["Orange", "Black Grapes", "Peaches", "Apple", "Kiwi", "Mango"] 

// Displaying set
myFavfruit.forEach{
   myRes in print(myRes)
}

Output

Black Grapes
Peaches
Apple
Mango
Orange
Kiwi

Conclusion

So this is how we can iterate over an set. Here don’t get confused if the order of set elements change because set is an unordered collection. All the discussed methods works well with any data types. You can use them according to your preference.

Updated on: 21-Apr-2023

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements