7

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'

Community
  • 1
  • 1
GiorgioE
  • 204
  • 2
  • 10

2 Answers2

11

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
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
  • 2
    I'd suggest to user another way of unwrapping such as default value with `??` : `(MyEnum(rawValue: 42) ?? MyEnum.error)` – Dulgan Dec 13 '16 at 13:45
5

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

pkamb
  • 33,281
  • 23
  • 160
  • 191
Dravidian
  • 9,945
  • 3
  • 34
  • 74
  • Thank you! My Basic fault. Now it works, so now if I remove case .none from mutating function, it would still have this case defined, even if I don't need to have next step after that state. That's what I was looking for. – GiorgioE Sep 04 '16 at 09:01
  • Documentation:- https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html.. :)Happy coding – Dravidian Sep 04 '16 at 09:02
  • 4
    It is also possible to add these cases in one line, so `case green, red, orange, none`. – pedrouan Sep 04 '16 at 09:16