0

I want to implement a switch statement with operators, like this:

let op: (Int, Int) = Random.choice([(+), (-), (*)])

switch op {
case (+): // Compiler error
    print("addition")
default: 
    break
}

But it gives the error:

Expression pattern of type '_' cannot match values of type '(Int, Int) -> Int'

I've tried syntax variation:

case +: // Another compiler error

Expected expression after unary operator

So, looks like the compiler doesn't even recognize the operator under case. Is it possible to make such switch statement work?

P.S. I'm not interested in pseudo-solutions like using random numbers instead of operators or creating a wrapper class for them.

kelin
  • 11,323
  • 6
  • 67
  • 104

0 Answers0