Swift ‘For’ loop

Suneet Agrawal
2 min readDec 3, 2021

--

For loops are used by every developer regularly. There is for-in as well as a for-each loop in Swift which has a bit different syntaxes. Both of them are used to iterate over a range, array, set or dictionary but have a bit different syntaxes.

This post was originally posted at https://agrawalsuneet.github.io/blogs/swift-for-loop/ and reposted on Medium on 03rd Dec 2021.

While comparing with other languages, I realized in Swift, there are few concepts which are completely different from java or any other another language for loops.

Wait! They are not this tough. In fact, they are very easy, interesting and helpful.

Let’s check one by one.

1. Simple for loop in java that iterates from some number to some number incrementing one on each loop pass.

Java code
for (int i = 0; i <= 10; i++){
System.out.print(i);
}

its equivalent Swift code

Swift code
for i in 1...10 {
print(i)
}

Things to notice

  • No need to declare the data type of variable.
  • If iterating over a range, we can use (closed range) operator.
  • The lower and upper (including) limit can be defined on both the sides of operator.

Please continue reading at https://agrawalsuneet.github.io/blogs/swift-for-loop/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--