Swift 开关盒 "not"

标签 swift switch-statement

我有两个枚举:

public enum ServerState {
  case Connecting
  case Open
  case LoggedIn
  case Closed
  case Error(NSError)
}

enum TransportLayerState {
  case Disconnected(NSError?)
  case Connecting
  case Connected
}

我需要在它们之间切换,如果 ServerState 设置为底层 TL 状态不可能的状态,则返回“false”。例如,如果 serverState == .Open && tlState == .Disconnected,它将返回 false。我正在尝试使用 switch 语句来执行此操作,但我发现我真正想要的是匹配其中一个状态不是特定状态的情况。例如:

switch (serverState, tlState) {
case (.Connecting, !.Connecting): return false
case (.Closed, !.Disconnected(.None)): return false
case (.Error(_), !.Disconnected(.Some(_)): return false
case (.Open, !.Connected), (.LoggedIn, !.Connected): return false
default: return true
}

显然这不起作用,因为您不能将 ! 放在 case 语句之前。我唯一的其他选择是指定所有允许 的情况,数量要多得多。指定限制并允许所有其他状态组合更有意义,但我不确定如何执行此操作。有任何想法吗?我也在努力避免嵌套的 switch 语句。

注意:我知道我可以使用 Swift 2 的 if case 来做到这一点,但我现在不能使用 Swift 2,因为这是生产代码。所以请用 Swift 1.2 中的解决方案回应。

最佳答案

由于所有模式都是按顺序检查的(并且第一个匹配“获胜”), 您可以执行以下操作:

switch (serverState, tlState) {

case (.Connecting, .Connecting): return true // Both connecting 
case (.Connecting, _): return false  // First connecting, second something else

case (.Closed, .Disconnected(.None)): return true
case (.Closed, _): return false

// and so on ...

所以一般来说,匹配其中一个状态不是特定状态的情况可以用两种模式来完成:第一个匹配状态, 第二个是通配符模式 (_) 然后匹配所有其他 例。

关于Swift 开关盒 "not",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31773679/

相关文章:

ios - 当父 View 改变大小时,如何告诉 subview 调整大小?

linux - bash 输出无效选项

python - python 中网络拓扑的表示

macos - 以编程方式快速格式化字符串

c - 初学者 : How to convert random generated number into number from 1 to 7

c - 在 switch-case 中使用花括号时的“break”语句

c - 枚举和一个以字符串形式返回月份名称的函数

swift - 交换变量

ios - UIViewControllerAnimatedTransitioning : screen keeps getting black under custom view

ios - 尝试使用 Swift 实现无限滚动时陷入无限循环