Is there a simple way to test if you match one of a set of enumerations?

隐身守侯 提交于 2019-12-10 23:08:56

问题


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

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