[swift-users] Checking for a specific enum case and value

Joe Groff jgroff at apple.com
Tue Dec 29 12:12:51 CST 2015


> On Dec 29, 2015, at 3:37 AM, Kristof Liliom via swift-users <swift-users at swift.org> wrote:
> 
> Hi,
> 
> What is the best way to do a one line check for an enum with a specific inner value? Example:
> 
> enum State {
> 	case Running, Stopped(Int32)
> }
> 
> func stoppedSuccessfully(state: State) -> Bool {
> 	return state == .Stopped(0) // So only return true if state is .Stopped and the inner value is 0
> }

We don't yet synthesize an `==` operator for enums when they have associated values. However, you can still use pattern matching with switch or if/guard case:

if case .Stopped(0) = state {
  return true
} else {
  return false
}

-Joe


More information about the swift-users mailing list