Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if enum does not match a pattern?

Note that I have read this post but that post uses a switch statement and it is supposed to do something (return true) when the pattern matches. I, on the other hand, don't want to do anything if the pattern matches and use an if-case statement.

I have this enum:

enum MyEnum {
    case a
    case b(Int)
    case c
    case d
}

Here's an instance of it:

let myEnum: MyEnum = .a

Now I want to do something if myEnum is not .b. Since .b has an associated value, I can't simply use an if statement check:

if myEnum != .b { // compiler error
    // do my thing here
}

So I must use an if-case statement to pattern match it:

if case .b(_) = myEnum {

} else {
    // do my thing here
}

But I really hate the use of the empty if clause. That just looks unswifty to me. I tried to naïvely do this:

if case .b(_) != myEnum { // compiler error!
    // do my thing here
}

Is there a better way to do this other than using an empty if clause?

I still have code that should run regardless of whether the pattern matches, so a guard statement won't work.

like image 752
Sweeper Avatar asked Dec 16 '16 21:12

Sweeper


Video Answer


2 Answers

This is purely minimal semantic change of your own code, but note that you can simply "discard" the empty if clause inline with the case pattern matching:

if case .b(_) = myEnum {} else {
    // do your thing here
}

or, leaving out the redundant pattern matching for the associated value of case b:

if case .b = myEnum {} else {
    // do your thing here
}

This looks somewhat like a guard clause, but without exiting the scope.

like image 109
dfrib Avatar answered Sep 28 '22 18:09

dfrib


You could use a guard:

guard case .b = myEnum else { 
    // do your stuff here
    return 
}

The downside is that you have to exit the scope...

like image 41
Cristik Avatar answered Sep 28 '22 17:09

Cristik