For-in vs For-each in Swift
For-in and for-each are different variants of for loops in swift which are used to iterate over a range, set or dictionary. Both provide the same functionality but has a few limitations or differences when it comes to conditional access.
This post was originally posted at https://agrawalsuneet.github.io/blogs/for-in-vs-for-each-in-swift/ and reposted on Medium on 03rd Dec 2021.
To understand their differences, let’s try to understand their examples in details first.
For-in loop
For-in loop is used to iterate over a range, set or dictionary using both the indexes as well an element based iteration.
for item in 0...5 {
print(item)
}let dictionary = ["Suneet": "Engineering", "Ballu": "Sales", "John": "Marketing"]
for (name, department) in dictionary {
print("\(name) is working in \(department) department")
}let set = ["Suneet", "Agrawal", "Ballu"]
for item in set {
print(item)
}
For-each loop
For-each loop can also be used to iterate over a range, set or dictionary using both the indexes as well an element based iteration.
(0...5).forEach{ item in
print(item)
}let dictionary = ["Suneet": "Engineering", "Ballu": "Sales", "John": "Marketing"]
dictionary.forEach{ name, department in
print("\(name) is working in \(department) department")
}let set = ["Suneet", "Agrawal", "Ballu"]
set.forEach{ item in
print(item)
}
Difference between for-in and for-each
1. Break and continue statements cannot be used in for-each loop
break and continue are the basic syntaxes of for loop which is used to either break the loop iteration or to continue to the next element.
Since for-each is not an operator but it’s a function, break and continue can’t be used inside a for-each iteration.