What is Swift Guard Case

⋅ 1 min read ⋅ Swift

Table of Contents

What is Guard Case syntax in Swift

The guard-case is a Swift syntax to allow us to precondition check for one specific enum case.

Let's create an enum as an example.

enum Direction {
case north
case south
case east
case west
}

We can use guard-case to match a single case like this.

let direction = Direction.north

guard case .north = direction else {
return
}

print("We are heading to north")

Here is the equivalent version of a switch statement.

switch direction {
case .north:
print("We are heading to north")
case .south, .east, .west:
break
}

How to use Guard Case syntax

guard-case has the following syntax.

  • The case pattern goes after a guard statement.
  • The case pattern followed by the assignment (=) statement.

Here is how it looks.


guard case pattern = enumValue else {}

The case pattern has the same syntax as the switch statement. You can use any pattern that is supported in the switch statement.

Let's see some examples.

Here is an enum with an associated value, Barcode. We will use this in the following examples.

enum Barcode {
case basic(Int)
case qrCode(String)
}

Guard case

We can use guard-case to match a single case with the following syntax.

let code = Barcode.qrCode("sarunw")

guard case .qrCode = code else {
return
}
print("QR Code")

Guard case let

And just like a normal switch statement, we can use let to bind an associated value of that enum.

let code = Barcode.qrCode("sarunw")

guard case let .qrCode(content) = code else {
return
}
print("QR Code: \(content)")

Read more article about Swift or see all available topic

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.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
Using SwiftUI in UIKit as UIView

Learn how to use a SwiftUI view as a UIView in a UIKit project.

Next
Where is Info.plist in Xcode 13

If you create a new SwiftUI project, you will no longer see Info.plist file. Let's learn about this change.

← Home