Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum Case not found in type

Tags:

enums

swift

enum Operator: Character {
    case Substract = "-"
    case Add = "+"
    case Multiply = "*"
    case Divide = "/"
}

I have enum above and a function declared below which checks if we have valid operator. e.g. isOperator("+")

func isOperator(_ symbol: Character)-> Operator? {        
        let op = Operator(rawValue: symbol)       
        switch op {
            case .Substract, .Add, .Multiply, .Divide:
                return op
            default:
                return nil
        }
    }

What compiler returns here is "Enum Case not found in type" means cases defined in my switch statement (.Add .. etc) is not available in Operator type. Why compiler not able to find case since op is an operator type which swift inver types atuomatically?

like image 629
manismku Avatar asked Aug 20 '17 05:08

manismku


2 Answers

Yes, Because your let op = Operator(rawValue: symbol) is optional and in switch case your are matching exact values. So you can apply optional in case while comparing. as like below.

func isOperator(_ symbol: Character)-> Operator? {
    let op = Operator(rawValue: symbol)
    switch op {
    case .Substract?, .Add?, .Multiply?, .Divide?:
        return op
    default:
        return nil
    }
}
like image 177
Jaydeep Vora Avatar answered Oct 03 '22 11:10

Jaydeep Vora


You have only 4 cases then you can

func isOperator(_ symbol: Character)-> Operator? {
    return Operator(rawValue: symbol)
}

But if you are going to have more in the future then it's better to use guard beforeswitch

func isOperator(_ symbol: Character)-> Operator? {
    guard let op = Operator(rawValue: symbol) else {
        return nil
    }

    switch op {
        case .Substract, .Add, .Multiply, .Divide:
            return op

        ...

    }
}

  • In the newest version of swift, swift 3, the naming convention of enums has changed. Every enum cases has followed camelCase rules.

  • When you use function name like isSomething then this function should return Bool

like image 32
Adrian Bobrowski Avatar answered Oct 03 '22 12:10

Adrian Bobrowski