0

What is Swift If Case

 1 year ago
source link: https://sarunw.com/posts/swift-if-case/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

You can easily support sarunw.com by checking out this sponsor.

Reliable mobile testing for iOS apps:

Sponsor sarunw.com and reach thousands of iOS developers.

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.

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

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

let direction = Direction.north

if case .north = direction {
print("North")
} else {
print("Wrong direction")
}

Here is the equivalent version of a switch statement.

switch direction {
case .north:
print("North")
case .south, .east, .west:
print("Wrong direction")
}

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.


if case pattern = enumValue {}

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.

In the following examples, we will use an enum with an associated value, Barcode.

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

If case

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

let code = Barcode.qrCode("sarunw")

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

}

If case let

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

let code = Barcode.qrCode("sarunw")

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

}

You can easily support sarunw.com by checking out this sponsor.

Reliable mobile testing for iOS apps:

Sponsor sarunw.com and reach thousands of iOS developers.

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK