Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 146 ยท Control Flow

if and else

Learn how Swift's if, else if and else statements work, why conditions must be Bool, how to bind optionals with if let, and how to use if as an expression since Swift 5.9.

A program that always does the same thing is not very useful. Control flow is how code makes choices and repeats work, and if is its simplest tool: run this code only when a condition is true. Swift's if should look familiar if you have used any C-family language, with three differences that make it safer and more pleasant: no parentheses around the condition, braces are always required, and the condition has to be a real Bool.

Since Swift 5.9, if can also be used as an expression that produces a value, which removes a lot of temporary var declarations. This lesson covers all of it, then looks at optional binding (if let), combining conditions, and common pitfalls. The next lessons continue with switch and Loops.

The basic if statement

An if statement has a condition and a block. The block runs only when the condition is true. Add else for the other case and else if for further alternatives; they are checked from top to bottom and only the first matching block runs.

Swift if, else if and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The temperature 24 fails the first test, passes the second and so prints It is warm.. The remaining branches are skipped even though 24 > 10 is also true: order matters, so put the most specific condition first. The second if has no else, which is fine, and the second call (5 degrees on a weekend) shows the other path. (The code sits in a function so that the compiler cannot see the constant values: with a plain let temperature = 24 it warns will never be executed for the dead branches.)

Two syntax rules differ from C, Java and JavaScript. The condition needs no parentheses (if temperature > 30 { rather than if (temperature > 30) {; adding them is allowed but considered noisy). And the braces are mandatory even for a single statement, which rules out the infamous bug where a second indented line looks like part of the if but is not.

Conditions must be Bool

Swift does not have "truthy" and "falsy" values. A number, a string or an optional is not a condition. You must write a comparison that produces a Bool, as you saw in Basic Types.

Swift A non-Bool condition (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler rejects both lines: error: type 'Int' cannot be used as a boolean; test for '!= 0' instead and error: cannot convert value of type 'String' to expected condition type 'Bool' (for the integer it even suggests the fix). Write what you mean: if count > 0 and if !name.isEmpty.

The assignment = is not allowed as a condition either, because assignment does not produce a value in Swift. So the classic typo if x = 5 is a compile error, not a silent bug.

Combining conditions

Use && (and), || (or) and ! (not) to combine tests (Operators explains short-circuiting). In an if you can also separate several conditions with commas, which means and, evaluated in order, left to right. The comma form is especially handy because a later condition can use something established by an earlier one.

Swift Combining conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The last if does two things in one condition list: let first = numbers.first unwraps the optional (an empty array would have no first element), and first > 3 then uses the unwrapped value. This is the idiom you will write most often.

Optional binding with if let

An optional is a value that might be missing. You cannot use it as if it were definitely there, so Swift makes you check. Optional binding does the check and the unwrapping together: if the optional contains a value, the value is bound to a new constant that is valid inside the braces. This is a first look; Optionals and Optionals in Depth cover the topic fully.

Swift if let and the shorthand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Int(text) returns an optional, because the text might not be a number. if let number = Int(text) runs the first block only when conversion succeeded, and number is a plain Int inside it (you cannot use it in the else). Since Swift 5.7 you can write if let nickname instead of if let nickname = nickname: the new constant has the same name and shadows the optional. The last example chains two bindings and a condition; if any step fails, the whole if is false. A related statement, guard let, is the better choice when you want the rest of the function to continue only on success; see guard and Early Exit.

if as an expression

Very often you want to choose a value based on a condition. The old way is a var that you assign in each branch:

Swift
let message: String
if score >= 50 {
    message = "pass"
} else {
    message = "fail"
}

Since Swift 5.9, an if can be an expression: each branch contains a single expression, and the if as a whole has the value of the chosen branch. It can initialize a constant, be assigned to a variable, be returned from a function or be thrown.

Swift if expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The expression form is only allowed where a value is assigned, returned or thrown; writing "a" + (if x { "b" } else { "c" }) fails with error: 'if' may only be used as expression in return, throw, or as the source of an assignment. Three rules keep if expressions predictable. Every branch must be present (there must be a final else), because the expression needs a value in every case. Every branch must be a single expression, with no extra statements, and all branches must have the same type. A function whose body is a single if expression returns it implicitly, as describe does without the word return. If you need several statements in a branch, use a normal if statement or compute the pieces first.

The compiler enforces the rules:

Swift An if expression without else (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The result is error: 'if' must have an unconditional 'else' to be used as expression. Add the else branch and it compiles. Mixing types, such as "text" in one branch and 0 in the other, is also an error, because the compiler cannot decide what type kind has.

Prefer an if expression over a ternary ?: when a branch is more than a trivial value or when you have more than two outcomes. Prefer the ternary for tiny inline choices such as count == 1 ? "" : "s".

Nested conditions and early exit

You can nest if statements, but deep nesting makes code hard to follow. If you find yourself writing three levels, flatten with combined conditions, or reverse the logic and exit early.

Swift Flattening nested conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both functions give identical answers (each line starts with true), but the flat one reads like a checklist: the problems are handled first and the successful path runs at the left margin. guard is the tool designed for that shape and is the topic of guard and Early Exit.

if case: a preview of pattern matching

if can also test whether a value matches a pattern, using if case. It is a lighter alternative to a full switch when you care about one case only.

Swift if case with ranges and enums

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

if case .flashing(let times) = signal checks the case and extracts the associated value in one step. The pattern is on the left of =, the value on the right. You will get the full story in Pattern Matching and switch.

Common pitfalls

  • Using = instead of ==. Swift refuses to compile it, but the message can confuse beginners. In if x = 5, replace it with x == 5.
  • Comparing optionals carelessly. if score > 50 where score is Int? does not compile; unwrap first, or compare against a value of the same optional type. (score == 5 on an optional is allowed, because == is defined for optionals whose wrapped type is Equatable.)
  • Floating-point equality. if total == 0.3 is risky after arithmetic (Basic Types). Compare against a tolerance.
  • Order of else if branches. The first true condition wins, so test the narrow case before the broad one.
  • Long chains. More than three or four else if branches on one value usually means a switch is clearer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is a valid Swift condition?

    Conditions must be Bool. An Int is not a Bool, an assignment is not an expression with a value, and an Int that is not optional cannot be compared with nil in a useful way.
  2. 2. In if let number = Int(text) { ... } else { ... }, where is number available?

    The binding exists only in the success branch; in the else branch the conversion failed, so there is nothing to use.
  3. 3. What must be true for let result = if flag { 1 } else { 2 } to compile?

    An if expression needs a value in every case: a final else, one expression per branch, and the same type everywhere.
  4. 4. What does if a, b, c { ... } mean?

    Comma-separated conditions act like && with ordering, and they may include optional bindings whose values later conditions use.
  5. 5. What is printed by: let n = 5; if n > 3 { print("A") } else if n > 1 { print("B") }?

    Only the first matching branch runs. Since n > 3 is true, A is printed and the else if is never checked.

Summary

  • if, else if and else need no parentheses around the condition, but always require braces; only the first true branch runs.
  • Conditions must be Bool; Swift has no truthy values, and = cannot appear as a condition.
  • Combine tests with &&, ||, !, or use commas in an if to require several conditions in order.
  • if let value = optional (or the shorthand if let optional) unwraps safely and scopes the value to the block.
  • Since Swift 5.9, if is an expression: every branch must be one expression of the same type and a final else is required.
  • Flatten nesting with combined conditions and guard; use if case for a quick one-pattern test.

Next: switch