0

Is there a way to abbreviate the following type of condition in Swift?

if ( (myEnum == .1 || myEnum == .2 || myEnum == .3 || myEnum == .8) && startButton.isSelected ) 

I tried typing:

if ( (myEnum == .1 || .2 || .3 || .8) && startButton.isSelected ) 

and:

if ( (myEnum == .1,.2,.3,.8) && startButton.isSelected )

but none of those worked. I also tried looking at documentation but can't find a similar example.

Thanks!

Nerdy Bunz
  • 6,040
  • 10
  • 41
  • 100
  • Related: https://stackoverflow.com/questions/33757555/shortening-if-else-from-ifx-y-x-z-to-ifx-y-z-in-swift. – Martin R Feb 09 '18 at 13:27
  • Also: https://stackoverflow.com/questions/32750139/how-to-compare-one-value-against-multiple-values-swift. – Martin R Feb 09 '18 at 13:52
  • Remember to accept the answers that have helped you. You have a lot of questions with answers that you have commented are correct but they are unaccepted. It gives back to those who help you (and you get rep for accepting them too) :D – Fogmeister Feb 09 '18 at 13:52
  • 1
    Yes, I will do that. In this case I was hesitating because while yours is the most helpful and wisest answer to me, someone else answered with the technically correct answer that I was looking for in the first place... but I'll go with yours since it's my decision to make after all. – Nerdy Bunz Feb 10 '18 at 10:31
  • @BooberBunz absolutely. No pressure from me. Just noticed that a lot of your questions were still waiting :-) feel free to accept any answer you like. I’d a better one comes along then change to that too :-) – Fogmeister Feb 10 '18 at 16:39

3 Answers3

8

I don't think there is a way to abbreviate it like you want but there is, perhaps, another way to approach the same thing...

extension YourEnum {
    var someCondition: Bool {
        switch self {
        case .1, .2, .3, .8:
            return true
        default:
            return false
        }
    }
}

By doing this your condition at the call site becomes...

if myEnum.someCondition, startButton.isSelected {
    doTheThing()
}

By using this approach your code become more readable too. You can now give your condition a sensible name which other developers (including your future self) will be able to understand. Where before I would have no idea why those cases were chosen.

It also allows you to use this condition in multiple places and have only one implementation of it. So if the requirement changes you can change it in one place.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
5
if [.a, .b, .c, .d].contains(myEnum) && startButton.isSelected {
    // etc.
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
3

For this case I like to use John Sundell's extension to equatable:

extension Equatable {
    func isAny(of candidates: Self...) -> Bool {
        return candidates.contains(self)
    }
}

You can then use it as:

if myEnum.isAny(of: .1, .2, .3, .8) && startButton.isSelected { .. }
kiwisip
  • 437
  • 1
  • 4
  • 12