Swift Switch case “not”

前端 未结 2 1098
暖寄归人
暖寄归人 2020-12-19 19:21

I\'ve got two enums:

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

enum TransportLayerState          


        
相关标签:
2条回答
  • 2020-12-19 19:43

    One possible answer I found was to make TransportLayerState equatable. In that case I could do this:

    switch serverState {
    case .Connecting where tlState != .Connecting: return false
    case .Closed where tlState != .Disconnected(nil): return false
    case let .Error(err) where tlState != .Diconnected(err): return false
    ...
    default: return true
    }
    

    I do end up having to write a bit of code in TransportLayerState enum to make it equatable, so not sure if it's worth the effort, but it does work.

    0 讨论(0)
  • 2020-12-19 19:44

    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.

    0 讨论(0)
提交回复
热议问题