Swift If-Else Statement

A Swift if-else statement chooses between two blocks of code. Swift executes the if block when its condition is true; otherwise, it executes the else block.

Use if-else when a program must handle both outcomes of a Boolean test, such as validating a value, checking a user state, comparing numbers, or selecting a message.

Swift If-Else Syntax

A Swift if-else statement has a condition, an if block, and an else block. The braces are required. Parentheses around the condition are optional and are normally omitted.

</>
Copy
if boolean_expression {
   /* if block statements */
} else {
   /* else block statements */
}

// rest of the statements

Swift evaluates boolean_expression at runtime. When it evaluates to true, only the statements in the if block run. When it evaluates to false, only the statements in the else block run. Program execution then continues with the statements after the conditional.

Boolean Conditions Required by Swift If-Else

The condition in a Swift if statement must produce a Bool value. Swift does not treat nonzero integers, nonempty strings, or non-nil objects as implicitly true.

</>
Copy
let score = 75

if score >= 50 {
    print("Pass")
} else {
    print("Fail")
}

The comparison score >= 50 evaluates to either true or false, so it is a valid condition. Writing only if score is not valid Swift because score is an Int, not a Bool.

Swift If-Else Example When the Condition Is True

In the following example, the integer variable a has the value 10. The condition a < 20 is true, so Swift executes the if block and skips the else block.

main.swift

</>
Copy
var a:Int = 10

/* boolean expression to check if a is less than 20 */
if a < 20 {
    /* if block statements */
    print("a is less than 20.")
} else {
    /* else block statements */
    print("a is not less than 20.")
}

print("rest of the statements")

Output

$swift if_else_example.swift
a is less than 20.
rest of the statements

Swift If-Else Example When the Condition Is False

In this example, a has the value 20. The condition a < 10 is false, so Swift skips the if block and executes the else block.

main.swift

</>
Copy
var a:Int = 20

/* boolean expression to check if a is less than 10 */
if a < 10 {
    /* if block statements */
    print("a is less than 10.")
} else {
    /* else block statements */
    print("a is not less than 10.")
}

print("rest of the statements")

Output

$swift if_else_example.swift
a is not less than 10.
rest of the statements

Swift Else-If Chain for Multiple Conditions

Use else if when more than two outcomes are possible. Swift checks the conditions from top to bottom and executes the first matching branch. Once a branch runs, the remaining branches are skipped.

</>
Copy
if condition1 {
    // Runs when condition1 is true
} else if condition2 {
    // Runs when condition1 is false and condition2 is true
} else {
    // Runs when all preceding conditions are false
}

The following example classifies a numeric score.

</>
Copy
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")
}

Output

Grade B

The order matters. Place the most specific or highest-priority condition first. In the example, checking score >= 60 before score >= 90 would incorrectly classify a score of 95 in the first matching branch.

Swift If Statement with Multiple Conditions

Combine Boolean expressions with logical operators when a branch depends on more than one test:

  • && is true only when both conditions are true.
  • || is true when at least one condition is true.
  • ! reverses a Boolean value.
</>
Copy
let age = 24
let hasTicket = true

if age >= 18 && hasTicket {
    print("Entry allowed")
} else {
    print("Entry denied")
}

Use parentheses when they make a compound condition easier to read, especially when mixing && and ||.

</>
Copy
let isAdmin = false
let isOwner = true
let accountIsActive = true

if (isAdmin || isOwner) && accountIsActive {
    print("Access granted")
}

Swift If-Let Optional Binding

Optional binding uses if let to check whether an optional contains a value and, when it does, unwrap that value safely for use inside the block.

</>
Copy
let username: String? = "Asha"

if let username {
    print("Signed in as \(username)")
} else {
    print("No username is available")
}

Output

Signed in as Asha

The else branch runs when username is nil. Optional binding avoids force-unwrapping with ! when the value may be absent.

Using Swift If-Else as an Expression

Modern Swift can use if-else as an expression when assigning or returning a value. Each reachable branch must produce a compatible result type.

</>
Copy
let temperature = 31

let message = if temperature >= 30 {
    "Hot"
} else if temperature <= 10 {
    "Cold"
} else {
    "Mild"
}

print(message)

Output

Hot

An if expression normally needs an else branch because a value must be available for every path. When one branch returns nil, an explicit optional type may be needed so Swift can infer the intended result.

Choosing Between Swift If-Else, Switch, and Guard

Use if-else for a small number of Boolean conditions or range checks. Use switch when matching many distinct values, ranges, tuples, enums, or patterns. Use guard for early-exit validation when the rest of a function should continue only after a condition succeeds.

Common Swift If-Else Mistakes

  • Using a non-Boolean condition: Write if count > 0, not if count.
  • Using assignment instead of comparison: Use == to compare values. Swift does not allow assignment as the condition of an if statement.
  • Ordering an else-if chain incorrectly: Put narrower or higher-priority checks before broader checks.
  • Forgetting boundary values: Decide whether a comparison needs > or >=, and test the exact boundary.
  • Creating deeply nested conditions: Extract repeated logic into named Boolean values or use guard for early exits.

Swift If-Else Frequently Asked Questions

Does a Swift if statement require an else block?

No. Use an if statement without else when code should run only for the true case. Add else when the false case also needs explicit handling.

Can a Swift if statement contain multiple conditions?

Yes. Combine Boolean conditions with &&, ||, and !. Swift also supports condition lists that include optional binding and pattern matching.

Why does Swift reject an integer or string as an if condition?

Swift requires an if condition to evaluate to Bool. It does not implicitly convert integers, strings, or optional values into true or false.

What is the difference between if-else and switch in Swift?

if-else is usually clearer for a few logical comparisons. switch is often clearer for many cases or when using enum cases, ranges, tuples, and pattern matching.

Can Swift if-else return a value?

Yes. Swift supports if expressions that can assign or return a value, provided the branches produce compatible types and all required paths provide a result.

Swift If-Else Editorial QA Checklist

  • Verify that every example uses a condition that evaluates to Bool.
  • Check true, false, and exact-boundary inputs for each comparison.
  • Confirm that an else if chain is ordered from the most restrictive condition to the broadest applicable condition.
  • Ensure output blocks match the branch that the sample input reaches.
  • Compile examples that use if expressions with a Swift toolchain that supports that syntax.

Summary of Swift If-Else

A Swift if-else statement executes one branch when a Boolean condition is true and another branch when it is false. Use else if for additional outcomes, logical operators for compound tests, if let for optional binding, and an if expression when the conditional should produce a value. Continue with the Swift Tutorial for related Swift control-flow topics.