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'
I was having an issue with the same error when converting an Int to a custom enum:
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:
switch MyEnum(rawValue: 42) ?? MyEnum.yourEnumDefaultCase {
case .error:
// no error!
break
default:
break
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.