我可以使用大小写枚举比较作为布尔表达式吗? [英] Can I use case enum comparison as a boolean expression?
问题描述
我有一个关联值的枚举:
I have an enum with associated values:
enum SessionState {
...
case active(authToken: String)
...
}
我可以使用 case let
比较具有关联值的枚举案例:
I can use case let
to compare enum cases with associated values:
if case .active = session.state {
return true
} else {
return false
}
但是我可以直接返回 case
作为布尔表达式吗?像这样的东西:
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)
推荐答案
不幸的是,您不能(直接)使用 case
条件作为 Bool
表达式。它们只能在 if
, guard
, while $ c $等语句中访问c>,
for
等
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.
这在语言语法,其中:
case-condition → case pattern initializer
然后将其用于条件
:
condition → expression | availability-condition | case-condition | optional-binding-condition
(其中表达式
表示 Bool
表达式)
然后将其用于条件列表
:
condition-list → condition | condition , condition-list
然后将其用于诸如 if
:
if-statement → if condition-list code-block else-clause opt
因此您可以看到不幸的是 case-condition
不是表达式,而是可以在给定语句中使用的特殊条件。
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 }()
否则,在 enum
以获得 Bool
以便检查给定的情况,如在此问答中。
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.
这篇关于我可以使用大小写枚举比较作为布尔表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!