if and switch expressions
suggest changeSince Swift 5.9, if and switch can be used as expressions, so they produce a value. You can put them on the right side of an assignment, after return, or as the body of a function, closure or computed property.
Before Swift 5.9 you had two choices. You could use the ternary operator, which gets hard to read past one condition. Or you could declare an uninitialized let and assign it in every branch of an if or switch statement:
let temperature = 31
let description: String
if temperature > 30 {
description = "hot"
} else if temperature > 15 {
description = "mild"
} else {
description = "cold"
}
This article also covers the if let name / guard let name shorthand added in Swift 5.7.
The examples were compiled and run with Swift 6.4 on Windows:
swiftc -swift-version 6 main.swift -o main.exe
if as an expression
Here is the same code with an if expression:
let temperature = 31
let description = if temperature > 30 {
"hot"
} else if temperature > 15 {
"mild"
} else {
"cold"
}
print(description)
Output:
hot
Each branch is a single expression, and its value becomes the value of the whole if. You don't write return or the variable name in the branches. The type of description is inferred as String.
switch as an expression
switch works the same way. Each case holds one expression:
enum Suit { case hearts, diamonds, clubs, spades }
let suit = Suit.clubs
let color = switch suit {
case .hearts, .diamonds: "red"
case .clubs, .spades: "black"
}
print(color)
let code = 404
let message = switch code {
case 200..<300: "success"
case 301, 302: "redirect"
case 404: "not found"
case let c where c >= 500: "server error \(c)"
default: "unknown"
}
print(message)
Output:
black
not found
A switch expression must be exhaustive, just like a switch statement. The color switch covers all cases of the enum, so it needs no default. Patterns, ranges, let bindings and where clauses work as usual.
Implicit return from functions, closures and properties
Swift 5.1 let a function, closure or computed property whose body is a single expression leave out return. An if or switch expression counts as that single expression. This is very handy for computed properties on enums with associated values:
enum Shape {
case circle(radius: Double)
case rect(width: Double, height: Double)
case square(side: Double)
var area: Double {
switch self {
case .circle(let r): .pi * r * r
case .rect(let w, let h): w * h
case .square(let s): s * s
}
}
var name: String {
switch self {
case .circle: "circle"
case .rect: "rectangle"
case .square: "square"
}
}
}
func sign(of n: Int) -> String {
if n > 0 { "positive" } else if n < 0 { "negative" } else { "zero" }
}
let shapes: [Shape] = [.circle(radius: 1), .rect(width: 2, height: 3), .square(side: 4)]
for s in shapes {
print(s.name, s.area)
}
print(sign(of: -5), sign(of: 0))
let labels = [3, -1, 0].map { n in
if n.isMultiple(of: 2) { "even" } else { "odd" }
}
print(labels)
Output:
circle 3.141592653589793
rectangle 6.0
square 16.0
negative zero
["odd", "odd", "even"]
Without the new feature, each case would need its own return.
You can also write return explicitly in front of the expression, and use throw the same way:
enum E: Error { case tooHigh, tooLow }
func classify(_ n: Int) -> String {
return if n < 0 { "negative" } else { "non-negative" }
}
print(classify(-3))
let rawLevel = 7
func check() throws {
throw if rawLevel > 5 { E.tooHigh } else { E.tooLow }
}
do { try check() } catch { print(error) }
Output:
negative
tooHigh
Where you can use them
An if or switch expression is allowed in only three places:
- as the value of a
return(explicit or implicit) orthrow - as the right side of an assignment or a variable declaration (
let x = ...,var x = ...,x = ...) - as the single-expression body of a function, closure or computed property
It can't be part of a larger expression. You can't add to it, and you can't pass it as a function argument:
let n = 5
let total = 10 + if n > 0 { 1 } else { 0 }
print(if n > 0 { "yes" } else { "no" })
Both lines fail:
error: 'if' may only be used as expression in return, throw, or as the source of an assignment
error: 'if' may only be used as expression in return, throw, or as the source of an assignment
Use the ternary operator for small inline cases like these, or assign the if to a local constant first.
Assigning to an existing variable or a stored property also works. This lets an initializer set a let property in one statement:
struct Settings {
let pageSize: Int
init(env: [String: String]) {
pageSize = if let raw = env["PAGE_SIZE"], let n = Int(raw), n > 0 {
n
} else {
20
}
}
}
print(Settings(env: ["PAGE_SIZE": "50"]).pageSize)
print(Settings(env: ["PAGE_SIZE": "abc"]).pageSize)
var status = "idle"
let pending = ["a.txt", "b.txt"]
status = if !pending.isEmpty { "working" } else { "idle" }
print(status)
let verbose = CommandLine.arguments.contains("-v")
let log: (String) -> Void = if verbose {
{ print("[log]", $0) }
} else {
{ _ in }
}
log("started")
Output when run as main.exe -v:
50
20
working
[log] started
The condition can use everything a normal if condition can, including optional binding and where clauses. The last example picks between two closures. Note that the closure literals are wrapped in an extra pair of braces, because the outer braces belong to the if.
The rules
Every branch is a single expression
A branch can't contain statements. Adding a print before the value is an error:
let n = 5
let s = if n > 0 {
print("checking")
"positive"
} else {
"other"
}
error: non-expression branch of 'if' expression may only end with a 'throw'
The same applies to switch. A local let inside a case is a statement, so this fails too:
func area(_ shape: String, _ size: Double) -> Double {
let result = switch shape {
case "square":
let side = size
side * side
default: 0.0
}
return result
}
error: non-expression branch of 'switch' expression may only end with a 'throw' or 'fallthrough'
When a branch needs several statements, go back to the statement form with a deferred let, or use an immediately called closure:
func describe(_ n: Int) -> String {
let kind: String
if n.isMultiple(of: 2) {
print("even branch")
kind = "even"
} else {
kind = "odd"
}
return kind
}
print(describe(4))
func describe2(_ n: Int) -> String {
let kind = {
if n.isMultiple(of: 2) {
print("even branch")
return "even"
}
return "odd"
}()
return kind
}
print(describe2(7))
Output:
even branch
even
odd
The compiler still checks that a deferred let is assigned exactly once on every path, so the first form is just as safe as the expression form.
if needs an else
An if expression must produce a value on every path, so it needs a final unconditional else:
let n = 5
let s = if n > 0 { "positive" }
error: 'if' must have an unconditional 'else' to be used as expression
All branches must have the same type
Each branch is type-checked on its own, and the results must agree. Swift doesn't look for a common type:
let useMetric = false
let x = if useMetric { 1 } else { 2.5 }
error: branches have mismatching types 'Int' and 'Double'
The fix is to state the type. The literals then take that type, and nil works for optionals:
let useMetric = false
let distance: Double = if useMetric { 1 } else { 2.5 }
print(distance)
let small: Int8 = switch distance { case ..<2: 1 default: 100 }
print(small)
let maybe: Int? = if distance > 10 { 42 } else { nil }
print(maybe as Any)
Output:
2.5
100
nil
The ternary operator behaves differently here: useMetric ? 1 : 2.5 compiles and gives a Double, because the ternary is type-checked as one expression.
A branch may throw or never return
A branch doesn't have to produce a value if it leaves the scope instead. It can throw, or call a function returning Never, such as fatalError:
enum ConfigError: Error { case badLevel(String) }
func parseLevel(_ s: String) throws -> Int {
let level = switch s.lowercased() {
case "debug": 0
case "info": 1
case "warn", "warning": 2
case "error": 3
default: throw ConfigError.badLevel(s)
}
return level
}
for input in ["INFO", "warning", "verbose"] {
do {
print(input, "->", try parseLevel(input))
} catch {
print(input, "->", error)
}
}
func unreachable(_ flag: Bool) -> String {
if flag { "ok" } else { fatalError("flag must be true") }
}
print(unreachable(true))
Output:
INFO -> 1
warning -> 2
verbose -> badLevel("verbose")
ok
See Throwing errors for more on throw.
Branches can nest
A branch can itself be an if or switch expression:
let score = 87
let isRetake = true
let grade = if score >= 90 {
"A"
} else if score >= 80 {
if isRetake { "B (retake)" } else { "B" }
} else {
switch score {
case 70..<80: "C"
case 60..<70: "D"
default: "F"
}
}
print(grade)
Output:
B (retake)
This is legal, but deep nesting quickly gets hard to read. Pull the inner part into a function or computed property when that happens.
if let and guard let shorthand
Swift 5.7 added a shorter way to unwrap an optional into a constant with the same name. Instead of if let name = name, write if let name:
func greet(_ name: String?) {
if let name {
print("Hello, \(name)!")
} else {
print("Hello, stranger!")
}
}
greet("Ana")
greet(nil)
func area(width: Double?, height: Double?) -> Double? {
guard let width, let height, width > 0 else {
return nil
}
return width * height
}
print(area(width: 2, height: 3) as Any)
print(area(width: 2, height: nil) as Any)
var retries: Int? = 2
if var retries {
retries += 1
print("local retries:", retries)
}
print("original:", retries as Any)
Output:
Hello, Ana!
Hello, stranger!
Optional(6.0)
nil
local retries: 3
original: Optional(2)
The shorthand works with if let, if var, guard let, guard var and while let. It can be mixed with other conditions in the same list. As the if var example shows, it still creates a new copy that shadows the optional. Changing the copy doesn't change the original. For other ways to get at an optional's value, see Unwrapping an optional.
It also works for properties used inside a method, where self. is implicit, and for the common guard let self in closures that capture [weak self] (see Reference cycles and weak references):
struct User {
var nickname: String?
func show() {
if let nickname {
print("nickname:", nickname)
}
}
}
User(nickname: "kj").show()
final class Loader {
var onDone: (() -> Void)?
func start() {
onDone = { [weak self] in
guard let self else { return }
self.finish()
}
onDone?()
}
func finish() { print("finished") }
}
let loader = Loader()
loader.start()
Output:
nickname: kj
finished
The name must be a plain identifier. You can't unwrap a member path such as user.nickname, because there would be no valid name for the new constant:
if let user.nickname {
print(user.nickname)
}
error: unwrap condition requires a valid identifier
Write if let nickname = user.nickname for that case.
Combining the two
The shorthand fits well into an if expression:
func label(for name: String?) -> String {
if let name { "user: \(name)" } else { "guest" }
}
print(label(for: "ana"))
print(label(for: nil))
Output:
user: ana
guest
When you only need a default value and no transformation, the nil-coalescing operator (name ?? "guest") is shorter still.
When to use which
- Use the ternary operator for a short choice between two values inside a larger expression, such as a function argument or string interpolation.
- Use an
ifexpression when there are more than two outcomes, or when the condition uses optional binding. - Use a
switchexpression to map an enum or a set of patterns to values, especially in computed properties. - Use the statement form with a deferred
letwhen a branch needs more than one statement.