For-in vs For-each in Swift

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.

For-in loop

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

(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

Please continue reading at https://agrawalsuneet.github.io/blogs/for-in-vs-for-each-in-swift/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store