Conditional enum switch with stored enum

纵然是瞬间 提交于 2019-12-24 01:19:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/37835037/conditional-enum-switch-with-stored-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!