Swift if Statement
A Swift if statement runs a block of code only when its condition evaluates to true. It is used for decisions such as checking a number, validating input, comparing values, testing multiple conditions, and handling optionals.
Unlike some programming languages, Swift requires the condition of an if statement to produce a Bool value. Integers, strings, and other values are not treated implicitly as true or false.
Swift if Statement Syntax
A Swift if statement has a Boolean condition followed by a block of statements enclosed in braces.
Following is the syntax for Swift if statement.
if boolean_expression {
/* set of statements */
}
// rest of the statements
The Boolean expression is evaluated at runtime. When it evaluates to true, Swift executes the statements inside the if block. When it evaluates to false, Swift skips that block.
Program execution then continues with the statements that follow the conditional block.
How Swift Evaluates an if Condition
- Swift evaluates the expression after the
ifkeyword. - The expression must return either
trueorfalse. - If it returns
true, the statements inside the braces run. - If it returns
false, the statements inside the braces are skipped. - Execution continues after the closing brace.
Swift if Example with a True Condition
In this example, the integer variable a contains 10. The condition a < 20 is true, so Swift executes the statement inside the if block.
main.swift
var a:Int = 10
/* boolean expression to check if a is less than 20 */
if a < 20 {
/* set of statements */
print("a is less than 20")
}
print("rest of the statements")
Output
$swift main.swift
a is less than 20
rest of the statements
The first message is printed because the condition is true. The final statement is outside the if block, so it runs regardless of the condition.
Another Swift if Example with the Same True Condition
The following existing example also assigns 10 to a and checks whether a is less than 20. Therefore, the condition is true and both messages are printed.
main.swift
var a:Int = 10
/* boolean expression to check if a is less than 20 */
if a < 20 {
/* set of statements */
print("a is less than 20")
}
print("rest of the statements")
Output
$swift main.swift
rest of the statements
Note: The displayed source code uses a true condition, while the retained output shows only the statement after the block. To demonstrate a false condition consistently, use the next example.
Swift if Example with a False Condition
Here, a is 20 and the condition checks whether it is less than 10. The condition is false, so Swift skips the statement inside the block.
var a: Int = 20
if a < 10 {
print("a is less than 10")
}
print("rest of the statements")
Output
rest of the statements
Swift if Statement with Comparison Operators
Comparison operators are commonly used to build Boolean conditions in Swift.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | count == 5 |
!= | Not equal to | status != 0 |
< | Less than | temperature < 20 |
> | Greater than | score > 50 |
<= | Less than or equal to | attempts <= 3 |
>= | Greater than or equal to | age >= 18 |
Swift if Statement with Multiple Conditions
Use logical operators to combine conditions. The && operator requires both conditions to be true, || requires at least one condition to be true, and ! reverses a Boolean value.
let age = 21
let hasValidID = true
if age >= 18 && hasValidID {
print("Access allowed")
}
Parentheses are not always required, but they can make a complex condition easier to read and can clarify the intended order of evaluation.
let isAdmin = false
let isOwner = true
let accountIsActive = true
if (isAdmin || isOwner) && accountIsActive {
print("Permission granted")
}
Swift if-else and else-if Conditions
Add an else block when one set of statements should run for a true condition and another set should run for a false condition.
let number = 7
if number % 2 == 0 {
print("Even number")
} else {
print("Odd number")
}
Use else if when several conditions must be checked in order. Swift stops at the first condition that evaluates to true.
let score = 82
if score >= 90 {
print("Grade A")
} else if score >= 75 {
print("Grade B")
} else if score >= 60 {
print("Grade C")
} else {
print("Needs improvement")
}
Swift if let for Optional Values
An optional may contain a value or nil. An if let statement checks whether the optional contains a value and, when it does, unwraps that value into a temporary constant or variable.
var username: String? = "Alex"
if let unwrappedName = username {
print("Welcome back, \(unwrappedName)!")
} else {
print("Guest user.")
}
Inside the first block, unwrappedName is a non-optional String. The else block runs when username is nil.
Swift if case for Pattern Matching
Use if case when a condition should match an enum case or another Swift pattern. This is useful when only one pattern needs to be tested and a full switch statement would be unnecessary.
enum NetworkState {
case idle
case loading
case loaded(Int)
case failed
}
let state = NetworkState.loaded(3)
if case let .loaded(itemCount) = state {
print("Loaded \(itemCount) items")
}
Swift if #available for iOS and macOS Versions
An if #available check lets an app use APIs that are available only on specified operating-system versions while providing a fallback for earlier versions.
if #available(iOS 17, macOS 14, *) {
print("Use the newer API")
} else {
print("Use the fallback implementation")
}
The asterisk covers other platforms. Availability checks should match the platforms and minimum versions relevant to the project.
Returning Early from a Swift if Statement
An if block can return a value from a function as soon as a condition is met. Statements after that return are not executed for that path.
func result(for score: Int) -> String {
if score >= 50 {
return "Pass"
}
return "Try again"
}
print(result(for: 72))
Common Swift if Statement Mistakes
- Using
=instead of==: Assignment and equality comparison are different operations. - Using a non-Boolean condition: Swift does not allow conditions such as
if number; write an explicit comparison such asif number != 0. - Forgetting optional unwrapping: Compare or use an optional only after handling its possible
nilvalue. - Writing overlapping else-if ranges: Put the most specific or highest-priority condition first.
- Creating deeply nested conditions: Combine clear predicates, extract helper functions, or use
guardfor early exits when appropriate.
Swift if Statement Review Checklist
- Confirm that every
ifcondition evaluates toBool. - Check boundary values for operators such as
<,<=,>, and>=. - Verify both the true and false execution paths.
- Test each branch of an
else ifchain, including the finalelse. - Check that optionals are unwrapped safely with
if letor another appropriate technique. - Confirm that availability checks include a suitable fallback path.
Swift if Statement FAQs
What is an if condition in Swift?
An if condition is a Boolean expression that controls whether Swift executes a block of code. The block runs only when the expression evaluates to true.
Can a Swift if statement contain multiple conditions?
Yes. Combine conditions with && for logical AND, || for logical OR, and ! for logical NOT. Add parentheses when they improve clarity.
What is the difference between if and if let in Swift?
A regular if tests a Boolean expression. An if let statement checks whether an optional contains a value and unwraps that value for use inside the block.
When should Swift if case be used?
Use if case when one enum case or pattern needs to be matched. Use a switch statement when several patterns or all possible cases need separate handling.
What does if #available do in Swift?
if #available checks the operating-system version at runtime so that version-specific APIs can be used only where they are supported.
Swift if Statement Summary
A Swift if statement executes code conditionally based on a Boolean expression. It can be combined with comparison and logical operators, extended with else and else if, used to unwrap optionals with if let, used for pattern matching with if case, and used for platform checks with if #available.
In this Swift Tutorial, we have learned Swift if conditional statement with the help of syntax and examples.
TutorialKart.com