In this tutorial you will learn about the Swift For in Loop and its application with practical example.
Swift For in Loop
The for in loop takes a collection of data(arrays, dictionaries, sets , or anything that provides an iterator) and iterate through the items one at a time in sequence.
Swift For In Loop Flow Diagram
Syntax:-
1 2 3 |
for item in items { // loop body } |
Here, items provides an iterator that allows us to fetch each of the single element from the given collection, and item hold the the current element fetched from the items.
Iterating Over Range Using For In Loop
In Swift, we can loop through the range elements using for-in loop as following –
Example:-
1 2 3 4 |
print("W3Adda - Swift Iterating Range using For In loop") for i in 1...5 { print("Hello world!. Value is \(i)") } |
Output:-
Iterating Over an Array Elements Using For In Loop
In Swift, we can loop through the array elements using for-in loop as following –
Example:-
1 2 3 4 5 |
var persons = ["John", "Doe", "Smith", "Alex"] print("W3Adda - Iterating Array Elements.") for person in persons { print(person) } |
Output:-
Iterating Over a Dictionary Using For In Loop
In Swift, we can loop through the dictionary elements using for-in loop as following –
Example:-
1 2 3 4 5 |
var students: [String:Int] = ["John" : 10, "Doe" : 20, "Alex" : 30] print("W3Adda - Iterating Dictionary Elements.") for (key, value) in students { print("\(key) - \(value)") } |
Output:-
Swift Iterating Over a Set Using For In Loop
In Swift, we can loop through the set elements using for-in loop as following –
Example:-
1 2 3 4 5 |
var persons: Set<String> = ["John", "Doe", "Smith", "Alex"] print("W3Adda - Iterating Set Elements.") for person in persons { print(person) } |
Output:-