How to check if the enum matches the pattern?

Please note that I read this post , but this post uses the expression switch and it should do something (returns true) when it matches the pattern. I, on the other hand, do not want to do anything if the template matches and uses the if-case statement.

I have this listing:

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

Here is an example:

 let myEnum: MyEnum = .a 

Now I want to do something if myEnum not .b . Since .b has a related meaning, I can't just use the if if check:

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

Therefore, I have to use the if-case statement to match the pattern:

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

But I really hate using the empty if clause. It just looks unattractive to me. I tried to naively do this:

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

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

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

+5
source share
5 answers

This is a purely minimal semantic change to your own code, but note that you can simply “discard” the empty if inline clause by matching the case pattern:

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

or, without considering the excessive pattern matching for the associated case b value:

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

This looks like a sentence guard , but does not go beyond the scope of the area.

+9
source

You can use guard :

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

The downside is that you need to get out of scope ...

+3
source

You can write a computed property and return the bool value to it, depending on the case.

 enum MyEnum { case a case b(Int) case c var isCaseB: Bool { switch self { case .b(_): return true default: return false } } } 

then in your clean check code:

 if !enumVal.isCaseB { } 

I checked the answer you mentioned in your question, but I wasn’t sure that you meant that you didn’t want to use the switch statement at all, or just don’t want to mix it with other code. I think this is a good and clean way to check before writing any kind of execution, depending on the case.

+1
source

What about:

 switch myEnum { case .b(_): break default: // do your thing here } 
+1
source

Create var for an enumeration that evaluates if your value is not .b(_) :

 enum MyEnum { case a case b(Int) case c case d var notB: Bool { switch self { case .b(_): return false default: return true } } } MyEnum.a.notB // true MyEnum.b(1).notB // false MyEnum.c // true MyEnum.d // true 

Not the biggest answer, as there is still a lot of code to check, but at least checking is only one line when you actually use it.

+1
source

Source: https://habr.com/ru/post/1261414/


All Articles