The power and limitations of using Swift statements as expressions
Since Swift 5.9, it’s possible to use Swift’s if and switch statements as expressions, meaning that the results of such statements can be assigned to variables and properties, and returned from functions and closures. That might seem like a small convenience feature in isolation, but it can really help improve readability and reduce unnecessary verbosity in certain situations.
So let’s explore how this language feature works, how it can be used, and also how it currently (as of Swift 6.4) cannot be used, including what some of the reasons for those limitations are.

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.
Return values
It’s very common for the return value of a function or computed property to depend on some form of condition, such as in the following case, where we’re returning a different string from a computed title property depending on what enum case that a given MediaType value currently matches:
enum MediaType {
case photo
case video
case audio
var title: String {
switch self {
case .photo: return "Photo"
case .video: return "Video"
case .audio: return "Audio"
}
}
}Since each branch within the above switch statement simply returns a string, that means that we can instead return the whole statement, simply by omitting the return keyword from each branch (and, we don’t even have to prefix our switch statement with the return keyword either, since Swift supports implicit single-expression returns) — like this:
enum MediaType {
case photo
case video
case audio
var title: String {
switch self {
case .photo: "Photo"
case .video: "Video"
case .audio: "Audio"
}
}
}That same pattern can be applied regardless of whether we’re implementing a computed property (like above), or if we’re instead modeling our logic using functions or inline closures. It can even be combined with other language features, such as async/await, and error throwing:
actor ArticleService {
...
func publish(_ article: Article) async throws -> Article {
var article = article
article.publishingDate = .now
article.author = loggedInUser
return if article.isDraft {
try await publishDraft(article)
} else {
try await publishLive(article)
}
}
}The above works because both our publishDraft and publishLive functions return an Article value. Note, however, that we have to duplicate try await in front of both of our async throwing function calls within our if statement, as such control flow keywords can’t (yet) be applied directly to a statement-based expression.
Assignments
Another type of situation in which using statements as expressions can be very useful is when conditionally assigning a value to a property or let/var declaration. For example, the following title constant’s value depends on a number of conditions, which we’ve currently implemented by first declaring the constant, and then assigning a value to it within a chain of if and else clauses:
func messageDidLoad(_ message: Message) {
let title: String
if message.isNotification {
title = "Notification"
} else if message.sender.id == loggedInUser.id {
title = "Your message to \(message.recipient.name)"
} else {
title = "Message from \(message.sender.name)"
}
...
}By instead using our if/else chain as an expression, we can merge the constant declaration and its various assignments, giving us a very neat result — without having to extract our logic into a utility function, or use a ternary expression (which can often become quite hard to read when multiple conditions are involved):
func messageDidLoad(_ message: Message) {
let title = if message.isNotification {
"Notification"
} else if message.sender.id == loggedInUser.id {
"Your message to \(message.recipient.name)"
} else {
"Message from \(message.sender.name)"
}
...
}The above pattern also works when assigning a value to a property, and with different if statement flavors, such as optional unwrapping:
func configureWelcomeView(forReturningUser returningUser: User?) {
welcomeView.title = if let returningUser {
"Welcome back, \(returningUser.name)!"
} else {
"Welcome!"
}
...
}We can also use the above technique when declaring static values as well, which is especially useful when working with language features that can only appear within if and guard statements, such as #available checks:
enum UIConfiguration {
static let isLiquidGlassUsed = if #available(anyAppleOS 26, *) {
true
} else {
false
}
}Looking at the above does make one wish that #available could also be used as an expression, and simply be assigned directly to our isLiquidGlassUsed constant, but perhaps that’s a Swift Evolution proposal for another day.
Throwing errors
Finally, if and switch statements can also be used to determine what error to throw from within a throwing context. For example, here we’re deciding whether to throw a NetworkError directly, or whether to wrap it within a dedicated UnauthenticatedError type:
func decodeNetworkResponse<T: Decodable>(
_ response: Result<Data, NetworkError>
) throws -> T {
switch response {
case .success(let data):
try JSONDecoder().decode(T.self, from: data)
case .failure(let error):
throw if error.statusCode == 401 {
UnauthenticatedError(rawValue: error)
} else {
error
}
}
}Note that above we’re actually using an if statement as an expression that’s in turn nested within a switch statement that’s also used as an expression. Pretty cool!
Limitations
So if and switch statements can be used as expressions specifically within the type of situations that we’ve explored so far; when returning, when assigning a value, and when throwing an error — and that’s it (as of today). That means that we currently can’t do something like the following, where we’re attempting to determine the value of an isEditable argument based on a switch statement:
let viewModel = PageViewModel(
page: page,
isEditable: switch loggedInUser.role {
case .admin, .editor: true
case .reader: false
}
)Now, different people will have varying opinions about whether being able to do something like the above is even a good idea to begin with (since deeply nested expressions can often end up hurting readability). But not being able to use if and switch statements as any kind of expression, but rather just a subset of possible ones, is arguably a bit confusing, or at the very least inconsistent.
Of course, there are a number of ways to work around that limitation, including moving that switch statement into a utility function, or a computed property within an extension on User.Role, or a dedicated value declared just above our PageViewModel initialization code.
Another option would be to use the fact that switch statements are allowed as closure return expressions, and wrap the statement in question within a self-executing closure (if we really want to keep everything contained within a single top-level expression):
let viewModel = PageViewModel(
page: page,
isEditable: {
switch loggedInUser.role {
case .admin, .editor: true
case .reader: false
}
}()
)Another limitation when using if and switch statements as expressions comes down to how type inference is performed for such statements. Take the following example, where we’re assigning an optional Image to an icon value, with our final else clause assigning nil:
func messageDidLoad(_ message: Message) {
...
let icon = if message.isUnread {
Image(icon: .badge)
} else if message.isFavorite {
Image(icon: .star)
} else {
nil
}
...
}As of Swift 6.4, the above won’t compile, since type inference is currently performed separately for each branch within a statement that’s used as expression. That means that when the compiler goes to type check the final else branch, all it sees is a context-less nil, which isn’t enough to infer that the expression refers to Image?. So in this case, we can either use nil as Image?, or simply add a type annotation to our icon declaration, to resolve that compiler error:
func messageDidLoad(_ message: Message) {
...
let icon: Image? = if message.isUnread {
Image(icon: .badge)
} else if message.isFavorite {
Image(icon: .star)
} else {
nil
}
...
}Now, the question is: why do these limitations exist? Why can’t we use an if or switch statement as any kind of expression, and why is type inference not supported across an entire statement-based expression? As is so often the case with software development — it all comes down to trade-offs.
If we take a look at the original proposal for this feature, SE-0380 (which I recommend reading, by the way, as it gives some really useful insights into the complexity of programming language design in general), then we can see that some of these limitations were indeed deliberate design decisions. For example, here’s a quote from that proposal regarding the type inference limitations:
... the impact of bidirectional inference on the performance of the type checker would likely prohibit this feature from being implemented today, even if it were considered preferable. This is especially true in cases where there are many branches.
And regarding the fact that this feature is only supported within a subset of expression types, the proposal mentions this under its “Future Directions” section:
This proposal chooses a narrow path of only enabling expressions in the 3 cases laid out at the start. This is intended to cover the vast majority of use cases, but could be followed up by expanded functionality covering many other use cases.
So perhaps in future versions of Swift, these limitations could start being addressed, which would arguably improve Swift’s consistency, even though it might also come with a substantial amount of added complexity.

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.
Conclusion
Being able to use conditional statements as expressions strikes a nice balance between maintaining readability and reducing verbosity, as it lets us omit duplicate keywords while still giving our conditional expressions a familiar structure.
I personally would love to be able to use this feature in more contexts, especially when passing arguments to functions, for example when using conditional values within SwiftUI modifiers. So hopefully this is an aspect of Swift that will continue to improve in future versions of the language, but what’s currently been implemented is already very useful, and something I use more or less daily when writing Swift code.
Thanks for reading!

