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

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:

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 ?

case let as swift

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.

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:

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.

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

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.

Ezoic

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?

John Montgomery's user avatar

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:

Gereon's user avatar

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.

aturan23's user avatar

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:

kovpas's user avatar

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.

Witek Bobrowski's user avatar

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 .

Hot Network Questions

case let as swift

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

This page requires JavaScript.

Please turn on JavaScript in your browser and refresh the page to view its content.

Steven Curtis

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

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

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:

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

  1. Sharkoon

    case let as swift

  2. 😀 Case let. Patterns

    case let as swift

  3. For wileyfox swift 2 / swift 2 plus Case Luxury PU Leather Back Cover Case For Wileyfox Swift 2

    case let as swift

  4. Case For Wileyfox Swift 2 / Swift 2 Plus Case 5.0 inch Luxury Matte TPU Back Cover Soft Case For

    case let as swift

  5. SWIFT CASE 1

    case let as swift

  6. Swift Case

    case let as swift

VIDEO

  1. Let'Swift Newsletter #73 같이 읽기 (하) (레츠 스위프트 뉴스레터)

  2. How to use TaskGroup to perform concurrent Tasks in Swift

  3. How to use Async Let to perform concurrent methods in Swift

  4. Taylor Swift Did all of that in Her Legendary Career 🥺🥰✨(© to the owner) #trending #taylorswift

  5. Judge to make decision on Alex Murdaugh's alleged financial crimes

  6. 국내 개발 콘퍼런스 모음.zip

COMMENTS

  1. 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.

  2. How Do I Write If Case Let in Swift?

    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.

  3. 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?

  4. Pattern Matching with case let

    Swift has a particular keyword for applying Pattern Matching: case let. Let's dive into examples. Enums. Pattern Matching is very useful while

  5. What is Swift If Case

    if-case is a Swift syntax to match only a single case of an enum. ... let direction = Direction.north if case .north = direction {

  6. Use "or" logic with multiple "if case" statements

    However, that doesn't compile. Is there another way to write this to make the logic work? swift · enums · boolean-logic · associated-value.

  7. If case let

    A Swift 5.6 if case let statement reference guide, with an if case let example and its switch case let equivalent.

  8. Control Flow

    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.

  9. 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

  10. Pattern Matching, Part 4: if case, guard case, for case

    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 }