I have been searching for many questions here, I found one with similar title Enum case switch not found in type, but no solution for me.
我一直在这里寻找很多问题,我发现一个类似标题的枚举案例开关没有找到类型,但没有解决方案。
I'd like to use enum with mutation of itself to solve question, what is the next traffic light color, at individual states.
我想使用带有自身变异的枚举来解决问题,在个别状态下,下一个交通灯颜色是什么。
enum TrafficLights {
mutating func next() {
switch self {
case .red:
self = .green
case .orange:
self = .red
case .green:
self = .orange
case .none:
self = .orange
}
}
}
I have put all cases as possible options and it's still returning error:
我已将所有案例作为可能的选项,它仍然返回错误:
Enum 'case' not found in type 'TrafficLights'
在'TrafficLights'类型中找不到枚举“案例”
2 个解决方案
#1
4
The cases must be declared outside of the function:
案例必须在函数之外声明:
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
}
}
}
Advisable:- Go through Enumeration - Apple Documentation
建议: - 通过枚举 - Apple文档
#2
11
I was having an issue with the same error when converting an Int to a custom enum:
在将Int转换为自定义枚举时,我遇到了同样错误的问题:
switch MyEnum(rawValue: 42) {
case .error:
// Enum case `.error` not found in type 'MyEnum?'
break
default:
break
}
The issue is that MyEnum(rawValue: 42)
returns an optional. Unwrap it or provide a non-optional to allow switching on the enum:
问题是MyEnum(rawValue:42)返回一个可选项。打开它或提供非可选项以允许打开枚举:
switch MyEnum(rawValue: 42) ?? MyEnum.yourEnumDefaultCase {
case .error:
// no error!
break
default:
break
}
#1
4
The cases must be declared outside of the function:
案例必须在函数之外声明:
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
}
}
}
Advisable:- Go through Enumeration - Apple Documentation
建议: - 通过枚举 - Apple文档
#2
11
I was having an issue with the same error when converting an Int to a custom enum:
在将Int转换为自定义枚举时,我遇到了同样错误的问题:
switch MyEnum(rawValue: 42) {
case .error:
// Enum case `.error` not found in type 'MyEnum?'
break
default:
break
}
The issue is that MyEnum(rawValue: 42)
returns an optional. Unwrap it or provide a non-optional to allow switching on the enum:
问题是MyEnum(rawValue:42)返回一个可选项。打开它或提供非可选项以允许打开枚举:
switch MyEnum(rawValue: 42) ?? MyEnum.yourEnumDefaultCase {
case .error:
// no error!
break
default:
break
}