Swift – Print Set
In this tutorial, we will learn how to print all elements of a Set in Swift programming.
To print all elements of a Set we shall iterate through all of the elements in the Set, using for loop, while loop or forEach loop, and print each of them.
Example 1: Print Set using for Loop
In this example, we have a set of even numbers. We shall use a Swift For Loop to iterate through the elements of the Set and print them.
main.swift
var evens: Set = [2, 4, 8, 14]
for even in evens {
print("even")
}
Output
14
2
4
8
Note that in a Swift Set, order of the elements is not saved. So, when you iterate through a Set, you get the elements of the Set randomly.
But it can be guaranteed that an element does not occur twice.
Example 2: Print Set using while Loop
In this example, we have a set of student names. We shall use a Swift While Loop and size of the Set to iterate through the elements of the Set and print them.
main.swift
var students: Set = ["John", "Surya", "Lini"]
var i=0
while i<students.count {
print(students[students.index(students.startIndex, offsetBy: i)])
i=i+1
}
Output
John
Surya
Lini
Note that the Swift Set is unordered and the index on the Set does not make sense. But if you want an implementation using the index, this is the example.
Example 3: Print Set using forEach
In this example, we have a set of odd numbers. We shall use a Swift ForEach to iterate on a Set and print all of the elements in it.
main.swift
var odds: Set = [3, 9, 7, 5]
odds.forEach{ odd in
print(odd)
}
Output
5
7
3
9
Conclusion
In this Swift Tutorial, we have learned to print a set using for loop, forEach and while loop with the help of Swift example programs.