← Swift tutorial

Swift

Conditionals

if/else if/else work as usual, no parentheses needed around the condition, unlike most other C-family languages in this tutorial.

Example: a time-of-day greeting

let hour = 14
let greeting: String

if hour < 12 {
    greeting = "Good morning"
} else if hour < 18 {
    greeting = "Good afternoon"
} else {
    greeting = "Good evening"
}

print(greeting)
Good afternoon

Swift's switch is also commonly used for multi-way branches, and unlike some languages, it doesn't silently fall through to the next case by default, each case is self-contained, which avoids a classic C/Java bug where a forgotten break lets execution accidentally continue into the next case.

Example
let hour = 14
let greeting: String

if hour < 12 {
    greeting = "Good morning"
} else if hour < 18 {
    greeting = "Good afternoon"
} else {
    greeting = "Good evening"
}

print(greeting)
Output
Good afternoon
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account