ios - 具有存储枚举的条件枚举开关

标签 ios swift enums switch-statement

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

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

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

现在是另一个可以接受方向参数的枚举。

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("")
}

但是我得到了错误...

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

有办法吗?

最佳答案

其实很简单:)

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

你的代码

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

不编译,因为 == 默认只为 枚举没有关联值。

关于ios - 具有存储枚举的条件枚举开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37835037/

相关文章:

ios - 我是否需要使用OBJC_ASSOCIATION_RETAIN_NONATOMIC释放@dynamic变量集?

iOS8 扩展 : share images between container and extension

ios - 通过 Segue 将数据传递给新的 ViewController

cocoa - 如何在 CoreData 中存储 typedef 枚举

objective-c - 为什么我不能在 Objective-C 中切换枚举

iphone - 使用Core Graphics绘制正方形或包含png?

ios - 如何获得用于 appium 测试的 iOS 应用程序构建?

ios - AWS Cognito iOS 登录委托(delegate)方法 `didCompleteStepWithError ` 未调用

ios - 如何获取模态呈现 View Controller 的 Root View 高度?

c# - 数据绑定(bind)枚举 - 命名空间中不存在名称 'StoreLocation'