Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional enum switch with stored enum

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?

like image 852
Fogmeister Avatar asked Oct 26 '25 20:10

Fogmeister


1 Answers

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.

like image 54
Martin R Avatar answered Oct 29 '25 10:10

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!