I\'ve got two enums:
public enum ServerState {
case Connecting
case Open
case LoggedIn
case Closed
case Error(NSError)
}
enum TransportLayerState
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.
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.