Swift Controle Flow Statements
We’ll be looking into the wide variety of statements that Swift has to offer. We’ll be largely covering swift for loop, swift while, repeat-while, and switch statements. If you’d like to use an online compiler for Swift, go for https://iswift.org/playground
Swift for loop
To iterate over a sequence without using subscripts (indexes) we use for loops shown below.
var numberArray = [2,4,6,8,10] for number in numberArray { print(number) }
Swift for–in loops using subscripts with lower and upper bounds syntax shown below
for i in lowerbound...upperbound { //do something }
import Foundation var numberArray = [2,4,6,8,10] for i in 0...4 { print(numberArray[i]) }
The array gets iterated from the lower-bound to the upper-bound (both inclusive) using the closed range operator (…). To iterate with the upper bound not included, we use the half-range operator (..<). An example is given below:
import Foundation var numberArray = [2,4,6,8,10] for i in 0..<4 { print(numberArray[i]) //doesn't print 10 }
[quote font=”georgia”]Note: If lower-bound > upper-bound there’ll be a crash.[/quote]
To print the array in reverse order we can use the reversed() function as shown below.
import Foundation var numberArray = [2,4,6,8,10] for i in (0...4).reversed() { print(numberArray[i]) }
The below code will crash
import Foundation var numberArray = [2,4,6,8,10] for i in 4..<0 { print(numberArray[i]) }
stride is a function from the Swift library that allows us to enter the start value, end value and the offset value to increment by as shown below:
import Foundation //count from 1 to 10 by 1 for i in stride(from: 1, to: 10, by: 1) { print(i) }
Ignoring value from each sequence
import Foundation for _ in 1...5 { print("Hello World") }
Underscore effectively gets rid of the value from each sequence. This usage is similar to the while loop and can be used for calculating the power of a number as shown below:
import Foundation let base = 3 let power = 4 var answer = 1 for _ in 1...power { answer *= base } print("\(base) to the power of \(power) is \(answer)")
Swift while loop
while loops through its body of statements until the condition becomes false.
import Foundation var i = 0 while i <= 5 { print(i) i = i + 1 }
[quote font=”georgia”]Note: conditions present in all the control flow statements such as while and for–in loops, if-else in Swift, unlike other languages aren’t enclosed in parentheses ().[/quote]
Swift repeat while loop
repeat–while loops while a condition is met. The difference between a while and a repeat–while loop is that the repeat loop executes the statements present in the body before checking the condition.
import Foundation var i = 1 repeat { print(i) i = i + 1 } while i < 5
[quote font=”georgia”]Note: repeat-while loop is similar to the do-while loop in C, JAVA.[/quote]
Swift switch statement
A switch statement considers a value and compares it against several possible matching patterns. An example is given below:
import Foundation let character: Character = "a" switch character { case "a": print("The first letter of the alphabet") //this gets printed. case "z": print("The last letter of the alphabet") default: print("Some other character") }
Unlike other languages switch statements in swift, finish as soon as the first case is matched. They don’t fallthrough other cases or require an explicit break statement. To explicitly fallthrough the cases the fallthrough keyword is required as shown under
import Foundation let character: Character = "a" switch character { case "a": print("The first letter of the alphabet") //this gets printed. fallthrough case "z": print("The last letter of the alphabet")//this gets printed too fallthrough default: print("Some other character") //this gets printed too }
Swift allows multiple cases to be appended in switch (separated by commas) as shown below.
import Foundation var myInt = 0 switch myInt { case 0, 1, 2: print("zero, one or two") //this gets printed. case 3,5,7: print("three, five or seven") case 4: print("four") default: print("Integer out of range") }
Values in switch cases can be checked for their inclusion in a certain range as shown below:
import Foundation var myInt = 5 switch (myInt) { case 0...5: print("First half") //this gets printed case 5..<10: print("Second half") default: print("Out of range") }
In the above code “First Half” is printed. Though the number 5 exists in both the cases, the first is printed since it met first. The second case ranges from 5 to 10 where 10 is not inclusive.
Swift where statement
The where keyword is used to add additional criteria inside the case.
import Foundation var myInt = 5 switch (myInt) { case 0...5 where myInt%2==0: print("First half only even accepted") case 5..<10: print("Second half only odd accepted") default: print("Out of range") }
Swift One-Side Ranges
Swift 4 has introduced one-sided ranges wherein the missing range is automatically inferred. The following example demonstrates the same.
import Foundation let stringArray = ["How", "you", "doing", "today", "??"] let lowerHalf = stringArray[..<2] //["How", "you"] let upperHalf = stringArray[2...] //["doing", "today", "??]