【问题标题】:Swift : Enum case not found in typeSwift:在类型中找不到枚举案例
【发布时间】:2016-09-04 08:51:21
【问题描述】:

我在这里搜索了很多问题,我找到了一个标题相似的问题Enum case switch not found in type,但没有解决我的问题。

我想使用自身突变的枚举来解决问题,即在各个州,下一个红绿灯颜色是什么。

enum TrafficLights {
    mutating func next() {
        switch self {
        case .red:
            self = .green
        case .orange:
            self = .red
        case .green:
            self = .orange
        case .none:
            self = .orange
        }
    }
}

我已将所有情况作为可能的选项,但它仍然返回错误:

在“TrafficLights”类型中找不到枚举“案例”

【问题讨论】:

  • 我很困惑,我认为如果所有情况都在变异函数内,它们不需要在要定义的函数之外。谢谢。
  • 我希望这不是用于真正的红绿灯...

标签: swift enums switch-statement mutating-function


【解决方案1】:

我在将 Int 转换为自定义枚举时遇到了同样的错误:

switch MyEnum(rawValue: 42) {
case .error:
    // Enum case `.error` not found in type 'MyEnum?'
    break
default:
    break
}

问题是MyEnum(rawValue: 42) 返回一个可选的。打开它或提供一个非可选的以允许打开枚举:

switch MyEnum(rawValue: 42) ?? MyEnum.yourEnumDefaultCase {
case .error:
    // no error!
    break
default:
    break
}

【讨论】:

  • 我建议用户使用另一种展开方式,例如使用 ?? 的默认值:(MyEnum(rawValue: 42) ?? MyEnum.error)
【解决方案2】:

case 必须在函数之外声明:

enum TrafficLights {

case green
case red
case orange
case none

mutating func next() {
    switch self {
    case .red:
        self = .green
    case .orange:
        self = .red
    case .green:
        self = .orange
    case .none:
        self = .orange
    }
  }
}

建议:- 通过Enumeration - Apple Documentation

【讨论】:

  • 谢谢!我的基本错误。现在它可以工作了,所以现在如果我从变异函数中删除 case .none,它仍然会定义这个 case,即使我不需要在那个状态之后进行下一步。这就是我一直在寻找的。​​span>
  • 也可以在一行中添加这些case,所以case green, red, orange, none.
猜你喜欢
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多