Is it possible to abbreviate this condition in Swi

2019-08-20 19:19发布

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!

3条回答
一纸荒年 Trace。
2楼-- · 2019-08-20 19:57

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 { .. }
查看更多
仙女界的扛把子
3楼-- · 2019-08-20 19:58
if [.a, .b, .c, .d].contains(myEnum) && startButton.isSelected {
    // etc.
}
查看更多
Luminary・发光体
4楼-- · 2019-08-20 20:01

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.

查看更多
登录 后发表回答