Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 413
GiorgioE Avatar asked Sep 04 '16 08:09

GiorgioE


2 Answers

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
}
like image 52
pkamb Avatar answered Nov 04 '22 01:11

pkamb


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

like image 40
Dravidian Avatar answered Nov 04 '22 01:11

Dravidian