SwSwift
BeginnerLesson 3 of 16

Conditions & Loops – Swift

if, switch with patterns, for-in, while, and ranges.

if needs no parentheses around the condition, but always curly braces around the block. The condition must be a Bool. For simple cases there is the ternary operator ? :.

let punkte = 73
if punkte >= 90 {
    print("excellent")
} else if punkte >= 70 {
    print("good")
} else {
    print("needs improvement")
}

let status = punkte >= 50 ? "passed" : "failed"
print(status)

switch is much more powerful than in C: it must be exhaustive (all cases or a default), does not fall through (no break needed), and matches ranges, tuples, types, and conditions with where.

let p = 85
switch p {
case 90...100:
    print("A")
case 70..<90:
    print("B")       // here
case 0..<70:
    print("C")
default:
    print("invalid")
}

let punkt = (2, -2)
switch punkt {
case (0, 0):
    print("origin")
case (let x, let y) where x == y:
    print("diagonal")
case (let x, let y) where x == -y:
    print("anti-diagonal")   // here
default:
    print("somewhere")
}

Loops: for-in runs over ranges and collections, while checks before each pass, repeat-while after. stride allows arbitrary step sizes, and labels control nested loops.

for i in 0..<3 { print("Round", i) }          // 0 1 2
for i in stride(from: 10, through: 0, by: -5) {
    print(i)                                        // 10 5 0
}
for (index, frucht) in ["Apple", "Pear"].enumerated() {
    print(index + 1, frucht)
}

var n = 0
while n < 3 { n += 1 }
repeat { n -= 1 } while n > 0
print(n)                                            // 0

aussen: for i in 0..<5 {
    for j in 0..<5 where i * j == 6 {
        print("\(i)*\(j)")                          // 2*3
        break aussen
    }
}
TipWith for _ in 1...3 { ... } you repeat without a counter variable. The range 1...3 includes the 3, 1..<3 does not. One-sided ranges like ..<5 or 2... exist for slices and patterns.
WarningA switch over an enum does not need a default if all cases are covered, and that is exactly what you want: if you add a case later, the compiler flags every place you forgot.