Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Switch case "not"

I've got two enums:

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

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

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
}

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.

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.

like image 280
Aaron Hayman Avatar asked Dec 20 '22 01:12

Aaron Hayman


1 Answers

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.

like image 193
Martin R Avatar answered Jun 15 '23 17:06

Martin R