Menu
Coddy logo textTech

If Statement

Part of the Fundamentals section of Coddy's Swift journey — lesson 26 of 86.

The if statement lets your program execute code only when a specific condition is true. This is the foundation of decision making in programming — your code can now respond differently based on different situations.

let temperature = 35

if temperature > 30 {
    print("It's hot outside!")
}

The code inside the curly braces runs only when the condition evaluates to true. If temperature were 25, nothing would be printed because the condition would be false.

You can use any expression that produces a Boolean value as your condition, including the comparison and logical operators you've already learned:

let age = 20
let hasID = true

if age >= 18 && hasID {
    print("Access granted")
}

Notice that Swift doesn't require parentheses around the condition, though you can add them if you prefer. The curly braces, however, are always required — even for single-line statements.

challenge icon

Challenge

Easy

You are provided with the following variables:

let speed = 85
let speedLimit = 80

Use an if statement to check if speed is greater than speedLimit.

If the condition is true, print Speeding ticket issued.

Cheat sheet

The if statement executes code only when a condition is true:

let temperature = 35

if temperature > 30 {
    print("It's hot outside!")
}

You can use comparison and logical operators in conditions:

let age = 20
let hasID = true

if age >= 18 && hasID {
    print("Access granted")
}

Parentheses around the condition are optional, but curly braces are always required.

Try it yourself

let speed = 85
let speedLimit = 80

// TODO: Write your code below
// Use an if statement to check if speed is greater than speedLimit
// If true, print "Speeding ticket issued"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals