Swift Switch 案例“不" [英] Swift Switch case "not"

查看:21
本文介绍了Swift Switch 案例“不"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个枚举:

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 State 不可能实现的状态,我需要在它们之间切换 if 并返回false".例如,如果 serverState == .Open && 它将返回 falsetlState == .Disconnected.我正在尝试使用 switch 语句来执行此操作,但我发现我真正想要的是匹配其中一个状态不是特定状态的情况.例如:

I need to switch between them if and return 'false' if the ServerState is set to a state not possible by the underlying TL State. For instance, it would return false if serverState == .Open && tlState == .Disconnected. I'm attempting to do this using a switch statement, but I'm finding that what I really want is to match a case where one of the state is not a specific state. For instance:

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 语句.

Obviously this doesn't work because you cannot place ! before a case statement. My only other option is to specify all the allowable cases, which are far more numerous. It makes more sense to specify the restrictions and allow all other state combinations, but I'm not sure how to do this. Any ideas? I'm also trying to avoid nested switch statements.

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

Note: I'm aware that I could do this using Swift 2's if case, but I can't use Swift 2 right now as this is production code. So please respond with solutions in Swift 1.2.

推荐答案

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

Since all patterns are checked sequentially (and the first match "wins"), you could do the following:

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 ...

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

So generally, matching a case where one of the state is not a specific state can be done with two patterns: The first matches the state, and the second is the wildcard pattern (_) which then matches all other cases.

这篇关于Swift Switch 案例“不"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆