Swift If Case Let
The Swift If-Case-Let syntax is a convenient shortcut to avoid a full switch statement when you only want to match a single case. The syntax always seems backwards to me so here’s a reminder of how to use it.

Case Let - A Recap
I’m using the Swift Result type to capture the results of a throwing expression. In this case, loading data from a file:
The Result type is an enum with a success and failure case both of which have an associated value. In my example, I would typically switch on the result:
The let binds the associated value to a variable that we can use in the body of the case. We can also write these as case let :
We can also add a where clause to further filter the matching cases:
The case let syntax is not restricted to switch statements. We can rewrite the switch as a series of if-case-let statements if we want:
Note that the value we were switching on ( result ) now becomes an initializer for the case statement. The last example written as a guard statement:
Finally, here’s an example of a for-in loop:
Replacing A Switch With If Case Let
A switch statement is fine when I have something to do for all (or most) of the cases. Here’s an example where I only care about the failure case. I’m encoding some model data and then writing it to a property list file:
The Data.write method is an extension I added on Data that converts the throwing data.write(to:) method to return a result of type Result<void,Error> . It either succeeds, returning void , or fails with an error. Switching over the result in this case is annoying:
Using the case-if-let syntax to replace the switch statement:
Or using the alternate version which I find slightly easier to remember as it’s closer to the original switch syntax:
I still find using the result value as the initializer for the case-let confusing but I prefer it over the more verbose switch version. What do you think? Do you have a favorite use for case let ?
Never Miss A Post
Sign up to get my iOS posts and news direct to your inbox and I'll also send you a PDF of my WWDC 2022 Viewing Guide

Unsubscribe at any time. See privacy policy .
How Do I Write If Case Let in Swift?
If case let is an abbreviated form of switch.
case let immediately precedes the candidate pattern in both versions. Confusingly though, when using if case let , the value comes after the = operator. So
is equivalent to:
let binds associated values
case let is a shortcut that lets you bind all subsequent associated values with just variable names. But you can write each let individually, just before the variable name:
Provide a single name to create a tuple of all associated values at once:
The ? is syntactic sugar to only match non-nil optionals:
Omit let entirely if you don't need the associated values:
Add conditions to if and guard using commas
Iterate using for , where and logical operators.
Use ? to iterate over just non-optional values, even when doubly nested in associated values:
Bind non-optional derived values in chained expressions
Really helpful if you need one non-optional assignment amidst a bunch of optional ones:
- Swift Pattern Matching In Detail - Benedikt Terhechte
- Pattern Matching In Swift - Ole Begemann
- Pattern Matching - Crunchy Development
- Pro Pattern-Matching in Swift - Nick Teissler, Big Nerd Ranch
- Using the power of switching with associated values to write elegant, logical, meaningful code - objc.io
Using and expressing "case let" statements
After seveal years with Swift, I still find it hard to use the if case let or while case let, even worse with opotional pattern if case let x?.
So, I would like to find an expression to "speak" case let more naturally.
Presently, to be sure of what I do, I have to menatlly replace the if case by the full switch statement, with a single case and default ; pretty tedious.
I thought of canMatch or canMatchUnwrap … with:
So, following would read
if case let x = y { // if canMatch x with y
if case let x? = someOptional { // if canMatchUnwrap x with someOptional
while case let next? = node.next { // while canMatchUnwrap next with node.next
Am I the only one with such problem ? Have you found a better way ?

Accepted Reply
have others found a trick to make it easier to think about
I think this breaks down into two steps:
Understanding patterns in general.
Dealing with the
For 2, it took me a while to remember the syntax (and, specifically, to remember that the value I’m testing goes on the right of the
For 1, I created myself a cheat sheet that summarises the 8 different pattern grammars and then refer to that (I can’t post it here, alas, because it’s intimately connected with other text that’s in no state to share).
Share and Enjoy — Quinn “The Eskimo!” Apple Developer Relations, Developer Technical Support, Core OS/Hardware
I don’t think anyone would claim that the
You’re asking whether there’s a better syntax that you can use right now.
Or you’re asking whether we can improve the language in the future.
The answer to the former is “No.” And if you’re looking to discuss the latter, your best option is to read up on the Swift Evolution Process .
Thanks Quinn.
Yes, I (hope) understand the syntax. But it is a serious effort each time to use (really powerful not very natural)).
So my point was : have others found a trick to make it easier to think about ; I'm not thinking of language change.
Maybe I just have to train myself more until it becomes natural ? 😉
I'm sure you internal document would have been much useful.
I'm sure [your] internal document would have been much useful.
Pack the bags it’s guilt trip time! (-:
Seriously though, I had some time this week so I decided to tidy this up and post it here. And, on the plus side, creating and verifying all the examples below gave me a much better understanding of how patterns work (-:
IMPORTANT This isn’t an “internal document” but rather a cheat sheet that I created for my own personal use. I hope you find it useful too, but be aware that it isn’t an official Apple document, hasn’t been formally reviewed, and if it contains any mistakes then they’re all my fault!
Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
There are eight types of patterns, summarised in the table below.
- These patterns are destructuring if any of their sub-patterns are destructuring.
Destructuring patterns allow you to pull apart a structured value. The can be used in any context. In contrast, matching patterns can only be used in:
- The case of a switch statement
- The catch clause of a do statement
- ( if | while | guard | for ) case statements
A type annotation is a colon followed by a type. For example, consider the following:
Note In these examples the syntax terms are taken directly from The Swift Programming Language .
Wildcard Pattern
A common use for a wildcard pattern is in a switch statement where you want to do a wildcard match for all possible values.
This wildcard case breaks down as follows:
Identifier Pattern
You use the identifier pattern with every if let statement.
The pattern breaks down as follows:
Note that this is not a value binding pattern; the let is part of the optional-binding-condition construct.
Value Binding Pattern
The following contains two instances of the value binding pattern.
The first instance breaks down as follows:
And the second:
Tuple Pattern
This snippet uses a tuple pattern to destructure the tuple coming back from enumerated()
Enumeration Case Pattern
Enumeration case patterns most commonly show up in the case of a switch statement.
There are two examples here. The first does not contain the trailing tuple pattern, and it breaks down as follows:
The second enumeration case pattern does contain the trailing tuple pattern, which in turn contains a value binding pattern wrapped around an identifier pattern.
Optional Pattern
The optional pattern is a short cut for an enumeration case pattern. You can rewrite the example above as:
Here the pattern in the second case breaks down as follows:
Type Casting Pattern
I most commonly use type casting patterns in catch clauses, but here’s an example of something completely different.
The pattern in the first case breaks down as follows:
And the one in the second like so:
Speaking of catch clauses, let’s break down some common patterns, starting with this:
My next example breaks down in the same way:
This example differs by having a where clause:
Finally, here’s how to catch one specific error:
Expression Pattern
Here’s some very bad code that uses the expression pattern for frog pluralisation.
The first case breaks down as follows:
Pattern Matching with case let
Today we will talk about Pattern Matching, one of my favorite features in Swift. Pattern Matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. Swift has a particular keyword for applying Pattern Matching: case let . Let’s dive into examples.
Pattern Matching is very useful while working with enums. As a part of “Maintaining State in Your ViewControllers” post , we talk about State enum, which describes the state of ViewController. Let’s see how we can efficiently use Pattern Matching with it.
While regular switching on enum with associated values we can also use case let keyword to match it to some pattern and assign associated value to a variable. Another beautiful option here is filtering associated value by using where keyword.
Optional in Swift is the enum with two cases, so you can apply Pattern Matching as we do it before with enums. But in the case of optionals, we have some additional features. Let’s check the example code.
value? here means the non-nil value of optional. So, it is the same as .some(value).
Another good use case for Pattern Matching can be tuples. Tuples often used as lightweight types for grouping some data. Let’s see how we can use Pattern Matching on a tuple which presents authentication data.
As you can see, we can apply to tuples all the matching features which we used with enums. We can also match the particular value to the tuple as we do for matching admin data.
case let with flow statements
I want to mention that you can easily use case let keyword with any flow control statement, let’s see how we can use it with if condition statements.
Same is possible with guard statement.
Another compelling case let usage is possible with for-in loops, we can easily filter items.
Today we discussed how powerful can be Pattern Matching in Swift, and how we can use it in daily development. Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next week!
What is Swift If Case
What is if case syntax in swift.
if-case is a Swift syntax to match only a single case of an enum.
Here is an example enum, Direction .
We can use if-case to match a single case like this.
How to use If Case syntax
if-case has the following syntax.
- The case pattern goes after an if statement.
- The case pattern followed by the assignment ( = ) statement.
Here is how it looks.
Let's see some examples.
In the following examples, we will use an enum with an associated value, Barcode .
We can use if-case to match a single case with the following syntax.
If case let
Why do we need if case.
The switch statement syntax forces you to handle all of the cases .
This is a good thing since it makes sure you always handle every case . The compiler will warn us when we introduce a new case or remove an old one.
The only time you will need to use the if-case syntax is when you only care about one specific case .
You may also like
- What is Swift Guard Case 16 Jan 2023
- Different ways to check for String prefix in Swift 09 May 2020
- Codable in Swift 4.0 09 Jul 2017
- How expensive is DateFormatter 13 Dec 2020
- New Formatters in iOS 15: Why do we need another formatter 30 Jun 2021
- How to read App Name, Version, and Build Number from Info.plist 17 May 2021
Enjoy the read?
If you enjoy this article, you can subscribe to the weekly newsletter. Every Friday , you'll get a quick recap of all articles and tips posted on this site . No strings attached. Unsubscribe anytime.
Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.
In this article, I will show you all 5 button styles you can use with SwiftUI Button in iOS.
Learn how to enable/disable the delete ability in SwiftUI List.

- Sponsorship
- Become a patron
- Buy me a coffee
- Privacy Policy
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Use "or" logic with multiple "if case" statements
Suppose I have an enum case with an associated value, and two variables of that enum type:
If I want to check if both variables match the general case with the associated value, I can do that with a comma:
But I need to check if either matches the case, with something like this:
However, that doesn't compile. Is there another way to write this to make the logic work?
- boolean-logic
- associated-value

4 Answers 4
I would resort to some sort of isBar property on the enum itself, so that the "a or b" test remains readable:

- I was hoping there'd be a better built-in way of doing it, but it looks like this is probably going to be the cleanest option. – John Montgomery Dec 4, 2018 at 21:51
- Why not simply var isBar: Bool { return self == .bar } – Sh_Khan Dec 4, 2018 at 22:03
- 5 Because that doesn't even compile – Gereon Dec 4, 2018 at 22:05
My solution for this sort of thing is:
A lot of the time I want it the other way, a single var that might be filtered based on several values:
but indeed, if there are associated values involved you have to make them equatable and define an operator.

You have to implement Equatable protocol for your enum:
Then the following code should work:
UPD: In case if you don't need to check associated value, you can do pattern matching like this:
- 1 This won't work well if you don't care about the associated value of case bar – Mike Mertsock Dec 4, 2018 at 21:32
- No, it won't work indeed. Updated the answer with a suggestion on how to make it work. Not as nice as if case though. – kovpas Dec 4, 2018 at 21:37
- Yeah, your update with the switch statement is the best general solution I could think of also. – Mike Mertsock Dec 4, 2018 at 21:38
My guess would be that if case and guard case are syntax sugar, and just a small feature supported by compiler to improve developer’s experience. In the first case you are using consecutive conditions, which is also just a language feature to replace && operator to make the code more readable. When you are using && or || operators, the compiler would expect to get two expressions that return boolean values. case .bar = var1 itself is not exactly an expression that could live alone, without some context in Swift, so it is not treat as an expression that returns a bool.
To summarise:
if case and guard case are simply syntax sugar, works together with if <expression>, <expression> syntax
&& and || are just logical operators that are basically a functions that expect two boolean arguments on both sides.
To solve your problem, use the good old switch statement. Hope it helps.

Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged swift enums boolean-logic associated-value or ask your own question .
- The Overflow Blog
- Developers think AI assistants will be everywhere, but aren’t sure how to...
- Visible APIs get reused, not reinvented sponsored post
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Why are most US news programs silent about Iran-Saudi deal announced at Beijing on March 10th?
- when did command line applications start using "-h" as a "standard" way to print "help"?
- Confusion+Diffusion comparison table? (e.g. with Avalanche Criterion / SAC)
- A metric characterization of the real line
- are there any non conventional sources of law?
- How to calculate the infinite sum
- Mixing liquids in bottles
- How to make those lines in Tikz?
- Why does Mathematica take so long to produce this sound?
- Is there a "Standard Algorithm" language, as used in academic papers?
- Series expansion using binomial theorem in Mathematica
- Can a bank sue someone that starts a bank run that destroys the bank?
- Including somebody with an unrelated degree as a coauthor?
- Why did my flight leave the gear down for the first 10 minutes of flight?
- What's an adjective/phrase for "as a matter of principle"?
- What is the cause of the constancy of the speed of light in vacuum?
- Did mechanical hard drives often malfunction in high elevation places such as Bogota?
- Who was Abraham’s Mother?
- How to place 2 equations in one line but each is numbered separately?
- Why is my struct destructed twice with `std::variant` and `std::monostate`?
- Four ones and four zeros
- Theoretical Computer Science vs other Sciences?
- Graphicx package is shrinking memoir pages?
- Are we estimating the Bernoulli parameter in Logistic Regression?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
Swift 5.7 references for busy coders
If case let.
If case let can be used with enums with associated values.
Switch case let equivalent:
Alternatively, let can be written before each variable name:
Same example as above:
Further reading
- Control Flow 📖 Official Swift Book
This page requires JavaScript.
Please turn on JavaScript in your browser and refresh the page to view its content.

Sep 20, 2021
Member-only
I’ve Finally Mastered Case Let In My Swift Code
You know how you can always do things better in life. Certainly you can. I’ve previously created a micro-project around downloading a JSON String and writing the result to the screen.
There is nothing special going on in terms of the completion — I’m just returning a closure ((Users) -> …
More from Steven Curtis
stevecurtis.me
About Help Terms Privacy
Get the Medium app

Steven Curtis
Text to speech
Pattern Matching, Part 4: if case, guard case, for case
Now that we’ve revisited the various syntaxes for pattern matching in part 1 , part 2 and part 3 , let’s finish this blog post series with some advanced syntax using if case let , for case where and all!
Let’s use what we saw in previous articles and apply them all to some advanced expressions.
This post is part of an article series. You can read all the parts here: part 1 , part 2 , part 3 , part 4
if case let
The case let x = y pattern allows you to check if y does match the pattern x .
Writing if case let x = y { … } is strictly equivalent to writing switch y { case let x: … } : it’s just a more compact syntax which is useful when you only want to pattern-match against one case — as opposed to a switch which is more adapted to multiple cases matching.
For example, let’s use an enum similar to the one from the previous articles:
Then we can write this 1 :
This is equivalent to the more verbose code:
if case let where
We can combine the if case let with a comma ( , ) – where each condition is separated by , – to create a multi-clause condition:
That can lead to quite powerful expressions that would otherwise need a complex switch and multiple lines only to test one specific case.
guard case let
Of course, guard case let is similar to if case let . You can use guard case let and guard case let … , … to ensure something matches a pattern and a condition and exit otherwise.
Combining for and case can also let you iterate on a collection conditionally. Using for case … is semantically similar to using a for loop and wrapping its whole body in an if case block: It will only iterate and process the elements that match the pattern.
for case where
Adding a where clause to that all can make it even more powerful:
💡 Note : Using for … where without the case pattern matching part is also a valid Swift syntax. For example you can write:
It is not using pattern matching (no case nor ~= ) so that’s a bit out of the scope of this article series, but it’s still totally valid and as useful as the other constructs presented here — as it avoids wrapping the whole body of your for within a big if (or starting it with a guard … else { continue } ).
Combining them all
Let’s finish this series with the Grand Finale: combine all that we learned from the beginning (including some syntactic sugar like x? we learned in the previous article):
This look might look a little complex, so let’s split it down:
- It uses map to transform the Array<Media> array mediaList into an array of tuples [(String?, String)] containing the title (if any) + the kind of item (as text)
- It only matches if title? matches — which is syntactic sugar to say if .Some(title) matches — the $0.title of each media. This means that it discards any media for which $0.title returns nil (a.k.a. Optional.None ) — excluding any WebSite in the process, as those don’t have any title )
- Then it filters the results to only iterate on those for which title.hasPrefix("Harry Potter") is true.
So in the end this will loop on every medium that has a title starting with “Harry Potter”, discarding any medium that don’t have a title — like WebSite — as well as any medium having a title that doesn’t start with "Harry Potter" — excluding the J.K. Rowling documentary from that iteration as well.
The code will thus output this, only listing Harry Potter books and movies:
Using neither pattern matching nor any where clause nor syntactic sugar that we learned in this article series, the code might have looked like this instead:
Some might find it more readable, but you can’t argue that using for case let (title?, kind) in … where … is really powerful and allow you to impress your friends make great use of for loops + pattern matching + where clauses altogether. ✨
This is the end of this “Pattern Matching” series. Hope you enjoyed it and learned some interesting stuff 😉
Next articles will be more focused back on some nice Swifty design patterns and architecture than on Swift syntax and language.
💡 Don’t hesitate to tell me on Twitter if you have any particular subject on Swift you want me blog about and give me some ideas for what to write about next!
Thanks to Frank Manno for updating the code samples of this article to Swift 3!
The order of arguments (pattern vs. variable) in that syntax can be troubling. To remember the order, just think of it as using the same case let Media.movie(…) syntax you use in a switch . That way, you’ll remember to write if case let Media.movie(…) = m instead of if case let m = Media.movie(…) which wouldn’t compile anyway — grouping the case with the pattern ( Media.movie(title, _, _) ) like you do in switch , and not with the variable to compare it to ( m ). ↩

IMAGES
VIDEO
COMMENTS
The Swift If-Case-Let syntax is a convenient shortcut to avoid a full switch statement when you only want to match a single case.
How Do I Write If Case Let in Swift? · if case let is an abbreviated form of switch · let binds associated values · Add conditions to if and guard using commas.
After seveal years with Swift, I still find it hard to use the if case let or while case let, even worse with opotional pattern if case let x?
Swift has a particular keyword for applying Pattern Matching: case let. Let's dive into examples. Enums. Pattern Matching is very useful while
if-case is a Swift syntax to match only a single case of an enum. ... let direction = Direction.north if case .north = direction {
However, that doesn't compile. Is there another way to write this to make the logic work? swift · enums · boolean-logic · associated-value.
A Swift 5.6 if case let statement reference guide, with an if case let example and its switch case let equivalent.
As soon as the default case is matched, the break statement ends the switch statement's execution, and code execution continues from the if let statement.
You know how you can always do things better in life. Certainly you can. I've previously created a micro-project around downloading a JSON
The case let x = y pattern allows you to check if y does match the ... but this is mandatory as all switch in Swift must be exhaustive }