What is Swift Guard Case
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
}
You can easily support sarunw.com by checking out this sponsor.
Debug 10x faster with Proxyman: Your ultimate tool to capture HTTPs requests/ responses, natively built for your iPhone and macOS. Special deal for Black Friday: Get 30% off for all Proxyman licenses with code “BLACKFRIDAY2024”.
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 ShareUsing SwiftUI in UIKit as UIView
Learn how to use a SwiftUI view as a UIView in a UIKit project.
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.