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
EasyYou are provided with the following variables:
let speed = 85
let speedLimit = 80Use 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"This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input