Swift ‘For’ loop


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.

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.

2. Now let’s say if I don’t don’t want to include the upper limit in the loop and break the loop if it hits the upper limit.

  
Java code
for (int j = 0; j < 10; j++) {
System.out.print(j); //this will print only up to 9
}

We can use the half-open range operator (..<).
  
Swift code
for i in 1..<10 {
print(i)
}

3. I want to increment it by 2 or some other number.

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

We can use stride function here
  
Swift code
for i in stride(from: 0, through: 10, by: 2) {
print(i)
}
//this will run till last value, in our case till 10


for i in stride(from: 0, to: 10, by: 2) {
print(i)
}
//this will run less then last value, in our case till 8

4. Wait, what if I want to run the loop in reverse order. Can I use 10...1 ?

  
Java code
for (int i = 10; i > 0; i--) {
System.out.print(i);
}
No, you can not use 10...1 directly as ... operator never works on the reverse ranges. It will give you below run time error.
  
Error
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.

You have to use reversed() function.
  
Swift code
for i in (0...10).reversed() {
print(i)
}
You can also change the step size with stride function.
  
Java code
for (int i = 10; i > 0; i -= 2) {
System.out.print(i);
}

Swift code
for i in stride(from: 0, to: 10, by: 2).reversed() {
print(i)
}

for i in stride(from: 0, through: 10, by: 2).reversed() {
print(i)
}
But please note that stride function overload to and through works on upper range, in both nomral as well as in reversed case.

5. What if I have a complex calculation instead of addition or subtraction in each step. Let’s say multiplication or division.

  
Java code
for (int k = 2; k <= 256; k *= 2) {
System.out.print(k);
}

Move to while loop, no other way
  
Swift code
var k = 2
while (k <= 256) {
print(k)
k *= 2
}

6. I want to iterate over an array now.

  
Java code
int[] arr = new int[5];
for (int item: arr) {
System.out.print(item);
}

Simple, use the in in Swift
  
Swift code
let arr = [0,1,2,3,4]
for element in arr {
print(element)
}

7. I want to use the position (index) also. How can I do that?

  
Java code
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}

Just use enumerated function.
  
Swift code
let arr = [0,1,2,3,4]
for (index, element) in arr.enumerated() {
print("The element at \(index) is \(element)")
}

8. I heard about some for foreach also. Can I use the same in Swift?

  
Java code
let arr = [0,1,2,3,4]
for element in arr {
print(element)
}

Just use foreach function.
  
Swift code
let arr = [0,1,2,3,4]
arr.forEach{ element in
print(element)
}

9. And what about Dicionary?

  
Java code
HashMap map = new HashMap();
map.put("Suneet","Engineering");
map.put("Ballu","Sales");
map.put("John","Marketing");

for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + " is working in " + entry.getValue());
}

Simple. Use in based iteration.
  
Swift code
let employee = ["Suneet": "Engineering", "Ballu": "Sales", "John": "Marketing"]
for (name, department) in employee {
print("\(name) is working in \(department) department")
}

No, I am a fan of foreach loop.

Ok, no problem, there you go.
  
Swift code
let employee = ["Suneet": "Engineering", "Ballu": "Sales", "John": "Marketing"]
employee.forEach { name, department in
print("\(name) is working in \(department) department")
}
And we are done. See I told you this will be very easy and interesting.