swiftenumsswitch-statementmutating-function

Swift : Enum case not found in type


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'


Solution

  • 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