Is it possible to abbreviate this condition in Swift?

风格不统一 提交于 2019-12-11 15:26:23

问题


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!


回答1:


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.




回答2:


if [.a, .b, .c, .d].contains(myEnum) && startButton.isSelected {
    // etc.
}



回答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 { .. }


来源:https://stackoverflow.com/questions/48706702/is-it-possible-to-abbreviate-this-condition-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!