Checking for a specific enum case and value

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
}

Thank You,
Chris

This is what I would do.

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
}

func stoppedSuccessfully(state: State) -> Bool {
    if case let State.Stopped(value) = state where value == 0 {
        return true
    } else {
        return false
    }
}

stoppedSuccessfully(.Running) // false
stoppedSuccessfully(.Stopped(0)) // true
stoppedSuccessfully(.Stopped(100)) // false

···

On Tue, Dec 29, 2015, at 06:37 AM, Kristof Liliom via swift-users wrote:

Thank You,
Chris

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

I'm not sure this can be done in one line since it generally requires if- or guard-case-let.

I'd do this two-liner:

    func stoppedSuccessfully(state: State) -> Bool {
        guard case let .Stopped(val) = state else { return false }
        return val == 0
    }

Or:

    func stoppedSuccessfully(state: State) -> Bool {
        guard case let .Stopped(val) = state where val == 0 else { return false }
        return true
    }

Stephen

···

On Dec 29, 2015, at 6:37 AM, Kristof Liliom via swift-users <swift-users@swift.org> wrote:

Hi,

What is the best way to do a one line check for an enum with a specific inner value?

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

···

On Dec 29, 2015, at 3:37 AM, Kristof Liliom via swift-users <swift-users@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
}