SyntaxStudy
Sign Up
Swift Conditionals and Loops
Swift Beginner 1 min read

Conditionals and Loops

Swift provides if/else, guard, switch, for-in, while, and repeat-while control flow statements. The switch statement is exhaustive — it must handle every case — and does not fall through by default. The guard statement is used for early exits. It requires an else branch that transfers control out of the current scope (return, throw, break, continue). This keeps the happy path un-indented. For-in loops iterate over any Sequence — arrays, ranges, dictionaries, strings, and more.
Example
// if / else if / else
let temp = 72
if temp > 90 {
    print("Hot")
} else if temp > 70 {
    print("Warm")
} else {
    print("Cool")
}

// guard for early exit
func process(name: String?) {
    guard let name = name, !name.isEmpty else {
        print("Invalid name")
        return
    }
    print("Processing: \(name)")
}

// switch - exhaustive, no fallthrough
let day = 3
switch day {
case 1:       print("Monday")
case 2:       print("Tuesday")
case 3...5:   print("Mid-week")
case 6, 7:    print("Weekend")
default:      print("Unknown")
}

// for-in
for i in 1...5 { print(i) }
for i in stride(from: 0, through: 10, by: 2) { print(i) }

let names = ["Alice", "Bob", "Charlie"]
for (index, name) in names.enumerated() {
    print("\(index): \(name)")
}

// while
var count = 0
while count < 5 { count += 1 }

// repeat-while (do-while equivalent)
repeat { count -= 1 } while count > 0