Swift If Else
An if statement runs a block of code only when its condition is true. Different conditions can send the program down different paths.
Running a block when true
The block runs only when the condition is true. A false condition skips the block and the program moves on.
let score = 80
if score >= 50 {
print("pass")
}A chain of conditions
The chain tests its conditions from the top. The score here passes the second test and prints its word.
let score = 65
if score >= 90 {
print("A")
} else if score >= 60 {
print("B")
} else {
print("C")
}An if inside an if
The inner if sits inside the outer block. Both conditions hold here, so the deepest print runs.
let age = 25
let member = true
if age >= 18 {
if member {
print("member entry")
}
}An if that gives a value
The whole if stands where a value belongs in the let line. The chosen word is stored and then printed.
let score = 45
let label = if score >= 50 { "pass" } else { "fail" }
print(label)Example
let marks = 58
if marks >= 90 {
print("excellent")
} else if marks >= 40 {
print("pass")
} else {
print("retry")
}
print("checked")Key points
- Use if with a condition and a block in braces.
- Use else to run a block when the condition is false.
- Use else if to test another condition after the first one fails.
- An if block can hold another if statement inside it.
- An if can stand on the right side of = and give a value to a variable.
In this example, marks holds 58. The first condition marks >= 90 is false, so its block is skipped. The else if condition marks >= 40 is true, so the program prints pass. The final print runs after the chain and shows checked.
Note
An if statement needs no else part when no fallback is wanted.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
A program sets temp to 30 and runs if temp > 25 { print("hot") } else { print("cool") }. What prints?