Swift’s “if” and “switch” expressions explained

Published on: May 14, 2024

In Swift, we sometimes want to assign a property based on whether a certain condition is true or false, or maybe based on the value of an enum. To do this, we can either make a variable with a default value that we change after checking our condition or we define a let without a value so we can assign a value based on our conditions.

Alternatively, you might have used a ternary expression for simple assignments based on a conditional check.

Here’s what a ternary looks like:

let displayName = object.isManaged ? object.managedName : object.name

This code isn’t easy to read.

Here’s what it looks like if I had written the exact same logic using an if statement instead.

let displayName: String

if object.isManaged {
  displayName = object.managedName
} else {
  displayName = object.name
}

This code is much easier to read but it’s kind of weird that we have to declare our let without a value and then assign our value afterwards.

Enter Swift 5.9’s if and switch expressions

Starting in Swift 5.9 we have access to a new approach to writing the code above. We can have switch and if statements in our code that directly assign to a property. Before we dig deeper into the rules and limitations of this, let’s see how an if expression is used to refactor the code you just saw:

let displayName = if object.isManaged {
  object.managedName
} else {
  object.name
}

This code combines the best of both worlds. We have a concise and clear approach to assigning a value to our object. But we also got rid of some of the unneeded extra code which means that this is easier to read.

We can also use this syntax with switch statements:

let title = switch content.type {
  case .movie: object.movieTitle
  case .series: "S\(object.season) E\(object.episode)"
}

This is really powerful! It does have some limitations though.

When we’re using an if expression, we must provide an else too; not doing that results in a compiler error.

At the time of writing, we can only have a single line of code in our expressions. So we can’t have a multi-line if body for example. There is discussion about this on the Swift Forums so I’m sure we’ll be able to have multi-line expressions eventually but for the time being we’ll need to make sure our expressions are one liners.

Subscribe to my newsletter