Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use case enum comparison as a boolean expression?

Tags:

enums

swift

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 the case as a bool expression? Something like:

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

A simple comparison doesn’t work either:

// Binary operator '==' cannot be applied to operands of type 'SessionState' and '_'
return (session.state == .active)
like image 516
zoul Avatar asked Jun 06 '17 13:06

zoul


1 Answers

Unfortunately, you cannot (directly) use a case condition as a Bool expression. They are only accessible in statements such as if, guard, while, for etc.

This is detailed in the language grammar, with:

case-condition → case ­pattern­ initializer­

This is then used in a condition:

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

(where expression represents a Bool expression)

This is then used in condition-list:

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

which is then used in statements such as if:

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

So you can see that unfortunately case-condition is not an expression, rather just a special condition you can use in given statements.

To pack it into an expression, you'll either have to use an immediately-evaluated closure:

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

Or otherwise write convenience computed properties on the enum in order to get a Bool in order to check for a given case, as shown in this Q&A.

Both of which are quite unsatisfactory. This has been filed as an improvement request, but nothing has come of it yet (at the time of posting). Hopefully it's something that will be possible in a future version of the language.

like image 65
Hamish Avatar answered Nov 17 '22 11:11

Hamish