Skip to main content

Working with Control Flow

1. Using If Statements

Structure Description Example
if Basic conditional statement
if condition {
    // code
}
if-else Conditional with alternative path
if condition {
    // code
} else {
    // alternative code
}
if-else if-else Multiple conditions
if condition1 {
    // code
} else if condition2 {
    // code
} else {
    // default code
}

Example: Basic If Statement

let temperature = 25
if temperature > 20 {
    print("It's warm outside")
}

Example: If-Else Statement

let score = 85
if score >= 90 {
    print("Grade: A")
} else {
    print("Grade: B or lower")
}

Example: If-Else If Statement

let grade = 75
if grade >= 90 {
    print("A")
} else if grade >= 80 {
    print("B")
} else if grade >= 70 {
    print("C")
} else {
    print("D or F")
}

2. Using Switch Statements

Feature Description Notes
Basic switch syntax switch value { case x: ...; case y: ...; default: ... } Matches value against cases
Fallthrough fallthrough Continues to next case without break
Range matching case 1...5: Matches a range of values
Tuple matching case (let x, let y) where x > y: Matches tuple values with conditions
Type matching case let x as String: Matches type and extracts value

Example: Basic Switch

let weather = "sunny"
switch weather {
case "sunny":
    print("It's a beautiful day!")
case "rainy":
    print("Don't forget your umbrella.")
default:
    print("Not sure about the weather.")
}

Example: Range Matching

let score = 85
switch score {
case 0...59:
    print("Fail")
case 60...89:
    print("Pass")
case 90...100:
    print("Excellent")
default:
    print("Invalid score")
}

Example: Tuple Matching

let point = (3, 4)
switch point {
case (0, 0):
    print("Origin")
case (_, 0):
    print("On x-axis")
case (0, _):
    print("On y-axis")
case let (x, y) where x > 0 && y > 0:
    print("First quadrant")
default:
    print("Other quadrant")
}
Note: Swift switch statements do not fall through by default, unlike C or Objective-C.
Warning: Every switch must be exhaustive. If a case is not covered, Swift will throw an error.

3. Using Pattern Matching in Switch

Pattern Description Example
.some(value) Matches an optional value that is not nil
let optionalValue: String? = "Hello"
switch optionalValue {
case .some(let value):
    print(value)
default:
    print("No value")
}
.none Matches an optional value that is nil
let optionalValue: String? = nil
switch optionalValue {
case .none:
    print("No value")
default:
    print("Value: \(optionalValue!)")
}
case let variableName as Type Matches a value and binds it to a variable of a specific type
let values: [Any] = [1, "Hello", 3.14]
for value in values {
    switch value {
    case let x as Int:
        print("Integer: $x)")
    case let y as String:
        print("String: $y)")
    default:
        print("Other type")
    }
}
case let variableName where condition Matches a value and applies a condition to it
let numbers = [1, 2, 3, 4, 5]
for num in numbers {
    switch num {
    case let x where x > 3:
        print("Greater than 3: $x)")
    default:
        print("Less than or equal to 3: $num)")
    }
}
case .some(.some(value)) Matches nested optionals
let nestedOptional: String?? = "Hello"
switch nestedOptional {
case .some(.some(let value)):
    print("Nested value: $value)")
default:
    print("No nested value")
}

Example: Pattern Matching with Tuples

let point = (3, 4)
switch point {
case (0, 0):
    print("Origin")
case (_, 0):
    print("On X-axis")
case (0, _):
    print("On Y-axis")
case let (x, y) where x == y:
    print("Equal coordinates: ($x, $y)")
default:
    print("Point at ($x, $y)")
}

Example: Pattern Matching with Arrays

let numbers = [1, 2, 3]
switch numbers {
case []:
    print("Empty array")
case [1]:
    print("Single element: 1")
case [1, 2, 3]:
    print("Specific array: [1, 2, 3]")
case [let first, let second, _]:
    print("First: $first), Second: $second)")
default:
    print("Other array")
}

4. Using For-In Loops

For-in loops in Swift are used to iterate over sequences such as arrays, ranges, dictionaries, and strings.

Sequence Type Syntax Description
Array for item in array { ... } Iterates over each element in the array
Range for index in 0..<5 { ... } Iterates over a range of integers
Dictionary for (key, value) in dictionary { ... } Iterates over key-value pairs
String for char in string { ... } Iterates over each character

Example: Iterating Over an Array

let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
    print(fruit)
}

Example: Iterating Over a Range

for i in 1...5 {
    print("Number: " + String(i))
}

Example: Iterating Over a Dictionary

let person = ["name": "John", "age": "30"]
for (key, value) in person {
    print("\(key): \(value)")
}

5. Using While Loops

Loop Type Description Usage
while Executes a block of code as long as the condition is true. while condition { code }
repeat-while Executes a block of code at least once, then continues while the condition is true. repeat { code } while condition

Example: Basic While Loop

var count = 0
while count < 5 {
    print("Count is: \\(count)")
    count += 1
}

Example: Repeat-While Loop

var number = 0
repeat {
    print("Number is: \\(number)")
    number += 1
} while number < 3
Note: The while loop may not execute at all if the condition is false initially. The repeat-while loop always executes at least once.

6. Using Break and Continue

Statement Description Usage
break Exits the innermost loop or switch statement Used inside loops or switch cases to terminate execution
continue Skips the rest of the current loop iteration and continues with the next Used inside loops to skip specific iterations

Example: Using break in a loop

for i in 1...10 {
    if i == 5 {
        break
    }
    print(i)
}
// Output: 1, 2, 3, 4

Example: Using continue in a loop

for i in 1...5 {
    if i == 3 {
        continue
    }
    print(i)
}
// Output: 1, 2, 4, 5

7. Using Fallthrough in Switch

Feature Description Usage
fallthrough Allows execution to continue into the next case in a switch statement switch value {<br>  case 1:<br>    print("One")<br>    fallthrough<br>  case 2:<br>    print("Two")<br>    fallthrough<br>  case 3:<br>    print("Three")<br>}

Example: Fallthrough in Switch

let number = 2<br><br>switch number {<br>&nbsp;&nbsp;case 1:<br>&nbsp;&nbsp;&nbsp;&nbsp;print("One")<br>&nbsp;&nbsp;&nbsp;&nbsp;fallthrough<br>&nbsp;&nbsp;case 2:<br>&nbsp;&nbsp;&nbsp;&nbsp;print("Two")<br>&nbsp;&nbsp;&nbsp;&nbsp;fallthrough<br>&nbsp;&nbsp;case 3:<br>&nbsp;&nbsp;&nbsp;&nbsp;print("Three")<br>&nbsp;&nbsp;default:<br>&nbsp;&nbsp;&nbsp;&nbsp;print("Other")<br>}
Note: fallthrough is rarely needed and can make code harder to read. Prefer explicit case handling.

8. Using Guard Statements

Feature Description Usage
guard Checks for conditions and exits early if the condition is not met. guard condition else { ... }
else Block executed if the guard condition fails. guard let value = optionalValue else { return }

Example: Basic Guard Usage

func processUserAge(_ age: Int?) {
    guard let userAge = age else {
        print("Age not provided")
        return
    }
    
    if userAge >= 18 {
        print("User is an adult")
    } else {
        print("User is a minor")
    }
}

Example: Guard with Multiple Conditions

func validateUser(name: String?, age: Int?) {
    guard let userName = name, !userName.isEmpty else {
        print("Name is required")
        return
    }
    
    guard let userAge = age, userAge >= 0 else {
        print("Valid age is required")
        return
    }
    
    print("User validated: \(userName), Age: \(userAge)")
}
Note: The guard statement is particularly useful for unwrapping optionals and ensuring preconditions are met early in a function, preventing deeply nested if statements.

9. Understanding Control Transfer

Statement Description Usage
break Exits the innermost loop or switch statement for i in 0...5 { if i == 3 { break } print(i) }
continue Skips the current iteration and continues with the next for i in 0...5 { if i == 3 { continue } print(i) }
fallthrough Allows execution to continue into the next case in a switch statement switch value { case 1: fallthrough case 2: print("1 or 2") }

Example: Using break in a loop

for i in 0...10 {
    if i == 5 {
        break
    }
    print(i)
}
// Output: 0, 1, 2, 3, 4

Example: Using continue in a loop

for i in 0...5 {
    if i == 3 {
        continue
    }
    print(i)
}
// Output: 0, 1, 2, 4, 5

Example: Using fallthrough in switch

let number = 2
switch number {
case 1:
    print("One")
    fallthrough
case 2:
    print("Two")
case 3:
    print("Three")
}
// Output: One, Two

10. Using Labeled Statements

Label Description Usage
label Identifier used to mark a loop or switch statement outerLoop: for i in 0..<3 { ... }

Example: Breaking from Nested Loops

outerLoop: for i in 0..<3 {
    for j in 0..<3 {
        if i == 1 && j == 1 {
            break outerLoop
        }
        print("i: $i, j: $j")
    }
}

Example: Continuing Nested Loops

outerLoop: for i in 0..<3 {
    for j in 0..<3 {
        if i == 1 && j == 1 {
            continue outerLoop
        }
        print("i: $i, j: $j")
    }
}

Was this article helpful?