DEV Community

Ajithmadhan
Ajithmadhan

Posted on

Swift - Control flow

Swift provides a variety of control flow statements. These include while loops to perform a task multiple times; if, guard, and switch statements to execute different branches of code based on certain conditions; and statements such as break and continue to transfer the flow of execution to another point in your code.

For-in loop

We use the for-in loop to iterate over a sequence, such as items in a array, range of numbers, or character in a string.

let names = ["Amna","Alex","Brain","Jack"]
for name in names {
print("Hello,\(name)")
// Hello,Amna
// Hello,Alex
// Hello,Brain
// Hello,Jack
}
Enter fullscreen mode Exit fullscreen mode

we can also use for-in loop with numeric ranges.

for index in 1...5 {
print(index)
//1
//2
//3
//4
//5
}
Enter fullscreen mode Exit fullscreen mode

Stride

Some might want fever times run the loop according to certain conditions, there we can use the stride(from:to:by:) function to skip the unwanted marks.

let min = 60
let minIntervals = 5
for tick in stride(from:0,to:min,by:minIntervals){
//renders tick every 5 mins
}
Enter fullscreen mode Exit fullscreen mode

for close ranges use stride(from:through:by)

While loop

A while loop performs a set of statements until a condition becomes false.

syntax:

while (condition) {
(statement)
}
Enter fullscreen mode Exit fullscreen mode

Repeat-while

The other variation of the while loop,known as repeated-while loop,performs a single pass through the loop block first,
before considering the loops condition.It then continues to repeat the loop untill the condition is false.

syntax:

repeat {
(statement)
} while (condition)
Enter fullscreen mode Exit fullscreen mode

Condition Statements

  • If
  • If...else
  • If...else if...else
  • switch

In Switch statements we don't want to explicitly mention "break" statement it automatically breaks the statement.

Where

A switch case can have a where clause to check for additional conditions.

example,

let point = (1,-1)
switch point {
case let(x,y) where x == y :
     print("Lies in line")
case let(x,y) where x = -y :
     print("in y axis")
default :
     print("default case")
Enter fullscreen mode Exit fullscreen mode

Compound cases:

  • multiple switch cases that shares same body.

example,

switch val{
case "a","e","i","o","u":
    print("Vowels")
default :
    print("constants")
}
Enter fullscreen mode Exit fullscreen mode

Control transfer statements

  • continue ->"I'm done with current loop iteration so start with next"
  • Break -> ends the execution of an entire control flow statement immediately
  • Fall through -> It forces the execution to fall through the switch case
  • return -> It returns from current context

Early exit

Guard statement

A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause—the code inside the else clause is executed if the condition isn’t true.

func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }

    print("Hello \(name)!")

    guard let location = person["location"] else {
        print("I hope the weather is nice near you.")
        return
    }

    print("I hope the weather is nice in \(location).")
}

greet(person: ["name": "John"])
// Prints "Hello John!"
// Prints "I hope the weather is nice near you."
greet(person: ["name": "Jane", "location": "Cupertino"])
// Prints "Hello Jane!"
// Prints "I hope the weather is nice in Cupertino."
Enter fullscreen mode Exit fullscreen mode

Using a guard statement for requirements improves the readability of your code, compared to doing the same check with an if statement. It lets you write the code that’s typically executed without wrapping it in an else block, and it lets you keep the code that handles a violated requirement next to the requirement.

Top comments (0)