Can I use enum case comparison as a boolean expression?

I have an enum with associated values:

enum SessionState {
    ...
    case active(authToken: String)
    ...
}

      

I can use case let

to compare enum cases with associated values:

if case .active = session.state {
    return true
} else {
    return false
}

      

But can I directly return case

as a bool expression? Something like:

// Error: Enum 'case' is not allowed outside of an enum
return (case .active = session.state)

      

Simple comparison doesn't work:

// Binary operator '==' cannot be applied to operands of type 'SessionState' and '_'
return (session.state == .active)

      

+3


source to share


1 answer


Unfortunately, you cannot (directly) use a condition case

as an expression Bool

. They are only available in such expressions as if

, guard

, while

, for

etc.

This is detailed in the language grammar :



case-condition → case ­pattern­ initializer­
      

This is then used in condition

:



condition → expression |­ availability-condition |­ case-condition­ | optional-binding-condition
      

(where expression

represents an expression Bool

)

This is then used in condition-list

:



condition-list → condition­ | condition ­, ­condition-list
      

­

which is then used in expressions like if

:



if-statement → if­ condition-list­ code-block­ else-clause­ opt­
      

So, you can see that, unfortunately, case-condition

it is not an expression, but just a special condition that you can use in these statements.

To package it into an expression, you will either need to use an immediately-evaluated closure:



return { if case .active = session.state { return true }; return false }()
      

Or else, write convenience computed properties on enum

to get a Bool

to check for a given case, as shown in this Q&A .

Both of these are pretty unsatisfactory. This one was filed as a request for improvement but nothing has come up yet (at the time of posting). Hopefully this will be possible in a future version of the language.

+3


source







All Articles