问题
Consider this code...
switch(testValue)
{
case .ValueA,
.ValueB,
.ValueC:
return 40
default:
return 0
}
Now if I was just checking for a single enumeration value, I could do this...
return (testValue == .ValueA)
? 40
: 0;
But I'm wondering how I can have something like the latter, but testing for multiples like the former, similar to this pseudo-code...
return (testValue is in [.ValueA, .ValueB, .ValueC])
? 40
: 0;
I know I can do it with an inline array, like so...
return ([SomeEnum.ValueA, .ValueB, .ValueC].Contains(testValue))
? 40
: 0;
...but I'm hoping there's something even cleaner. Is there?
回答1:
extension SomeEnum {
func isOneOf(values: Value...) -> Bool {
return values.contains(self)
}
}
return testValue.isOneOf(.ValueA, .ValueB, .ValueC) ? 40 : 0
来源:https://stackoverflow.com/questions/38336982/is-there-a-simple-way-to-test-if-you-match-one-of-a-set-of-enumerations