4

I'd like this code to work.

I have an enum where the case Direction.Right takes a distance parameter.

enum Direction {
    case Up
    case Down
    case Left
    case Right(distance: Int)
}

Now another enum that can take a Direction parameter.

enum Blah {
    case Move(direction: Direction)
}

let blah = Blah.Move(direction: Direction.Right(distance: 10))

When I switch on the Blah enum I want to be able to conditionally switch on the Move.Right like this...

switch blah {
case .Move(let direction) where direction == .Right:
    print(direction)
default:
    print("")
}

But I get the error...

binary operator '==' cannot be applied to operands of type 'Direction' and '_'

Is there a way to do this?

3
  • 2
    Your case .Move(let direction) where direction == .Up: works just fine for me. Commented Jun 15, 2016 at 12:17
  • @MartinR hmm.. I get Binary operator == cannot be applied to operands of type Direction and _ with that. May be a clean and build problem though. I'll take a look thanks. Commented Jun 15, 2016 at 12:19
  • @MartinR ah, it seems if you add a distance to the Direction then it goes wrong. Let me edit... Commented Jun 15, 2016 at 12:24

1 Answer 1

8

It is actually quite easy :)

    case .Move(.Up):
        print("up")
    case .Move(.Right(let distance)):
        print("right by", distance)

Your code

    case .Move(let direction) where direction == .Right:

does not compile because == is defined by default only for enumerations without associated values.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent. Makes perfect sense too. Was about to edit in the parameter. Thanks :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.