问题
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