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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With