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?
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
}
}
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 is
Something
then this function should return Bool
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