← Back to archive

Development · Swift

Swift conditionals: if-else and switch

Choose between Boolean conditions and pattern matching, and use ranges and fallthrough deliberately.

Read the Korean original on Velog ↗English translation

Development archive cover

Conditionals let a program choose behavior based on its current state. Swift uses if-else for Boolean conditions and switch for matching a value against patterns.

Control flow with if-else

An if condition must be a Bool; parentheses are optional. Conditions are checked in order, and only the first matching branch runs.

let score = 75

if score >= 80 {
    print("A")
} else if score >= 60 {
    print("B")
} else {
    print("C")
}

Pattern matching with switch

A switch is useful when comparing one value against several values or ranges. It must be exhaustive, so add default if the listed cases do not cover every possibility.

switch score {
case 80...100: print("A")
case 60..<80: print("B")
default: print("Keep going")
}

Each case ends automatically. Use fallthrough only when execution should deliberately continue into the next case. Use if-else for varied conditions and switch when matching a single value against several patterns.

← Back to archive