【问题标题】:Conditional enum switch with stored enum具有存储枚举的条件枚举开关
【发布时间】:2016-06-15 12:07:53
【问题描述】:

我希望这段代码能够工作。

我有一个枚举,其中的 case Direction.Right 采用距离参数。

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

现在是另一个可以采用 Direction 参数的枚举。

enum Blah {
    case Move(direction: Direction)
}

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

当我打开 Blah 枚举时,我希望能够像这样有条件地打开 Move.Right...

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

但我得到了错误...

二元运算符“==”不能应用于“Direction”和“_”类型的操作数

有没有办法做到这一点?

【问题讨论】:

  • 你的 case .Move(let direction) where direction == .Up: 对我来说很好用。
  • @MartinR 嗯.. 我得到了Binary operator == cannot be applied to operands of type Direction and _。可能是一个干净和构建的问题。我去看看谢谢。
  • @MartinR 啊,似乎如果您将distance 添加到Direction 中就会出错。让我编辑...

标签: ios swift enums switch-statement


【解决方案1】:

其实很简单:)

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

你的代码

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

无法编译,因为== 默认仅定义为 没有关联值的枚举。

【讨论】:

  • 优秀。也很有意义。即将在参数中进行编辑。谢谢:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多