问题描述
我有一个带有与此相关的值的枚举:
I have an Enum with associated values like this one:
enum SomeState {
case loggedOut(redirectAfterLogin: Module? = nil)
case loggedIn
}
现在,在某些情况下,我想精确比较两个状态(例如都已注销,并且重定向目标是否相等),有时我只想知道它们是否都已注销.我的问题涉及第二种情况:我想检查状态是否已注销并将其写入变量,但是显然我不能实现 Equatable
来解决这个问题忽略参数的一般情况.
Now in some cases I want to compare two states exactly (like are both logged out and also is the redirect target equal) and sometimes I just want to know if they are both logged out. My question regards the second case: I want to check if the state is logged out and write that to a variable, but obviously I can't implement Equatable
to just account for the general case ignoring the parameters.
一种实现此目的的方法是在Enum本身上实现计算属性 isLoggedOut
,但是由于这只是一个示例,而我的实际代码要大得多,因此对于我.
One way of achieving this would be to implement a computed property isLoggedOut
on the Enum itself, but since this here is just an example and my actual code is much larger, this is not an option for me.
第二种方式(我当前使用的方式)是:
A second way (the one I currently use) is this:
func whatever() {
if case .loggedOut = self.state {
self.isLoggedOut = true
} else {
self.isLoggedOut = false
}
}
这行得通,但我宁愿这样写:
This works, but I would rather write something like this:
func whatever() {
self.isLoggedOut = (case .loggedOut = self.state)
}
我是否遗漏了一些东西,还是真的不可能直接将 if
-子句的大小写比较写到变量(或类似的单行解决方案)上?
Am I missing something or is it really not possible to write the case comparison of the if
-clause to a variable directly (or some similar one-line-solution)?
推荐答案
您只需要将任何内容
更改为计算属性而不是函数,将分配修改为 isLoggedOut
成为 return
语句,您就拥有了 isLoggedOut
属性.
You simply need to change whatever
to be a computed property rather than a function, modify the assignments to isLoggedOut
to be return
statements and you've got your isLoggedOut
property.
var isLoggedOut: Bool {
if case .loggedOut = self.state {
return true
} else {
return false
}
}
简化的示例代码,其中包含 state
属性的类型也定义了 isLoggedOut
属性:
Simplified example code where the type holding the state
property defines the isLoggedOut
property as well:
enum SomeState {
case loggedOut
case loggedIn
}
struct User {
var state: SomeState
var isLoggedOut: Bool {
if case .loggedOut = self.state {
return true
} else {
return false
}
}
}
这篇关于将枚举大小写检查写入不符合Equatable一致性的Bool变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!