KK7 - 1 year ago 70

Swift Question

I'm trying to learn more about recursive enums.

Here's my code:

`enum Operation {`

case Unary((Double) -> Double)

case Binary((Double, Double) -> Double)

indirect case Combined(Operation, Operation)

}

let x = 7.0

let y = 9.0

let z = x + y

let plus = Operation.Binary{$0 + $1}

let squareRoot = Operation.Unary{sqrt($0)}

let combined = Operation.Combined(plus, squareRoot)

switch combined {

case let .Unary(value): value(z)

case let .Binary(function): function(x, y)

case let .Combined(mix): mix(plus, squareRoot)

}

How can I perform

`plus`

`squareRoot`

I keep getting this error:

Cannot call value of non-function type (Operation, Operation)

Answer

With `.Unary`

and `.Binary`

you are doing it right. You are retrieving the functions and executing them.

With `.Combined`

however, you are retrieving a tuple of operations and using it as if it were a function. What you should do, is to retrieve the functions within the tuple and execute them.

Instead of your switch you could use a recursive function, like this:

```
func handleOperation(operation: Operation) {
switch operation {
case let .Unary(value): value(z)
case let .Binary(function): function(x, y)
case let .Combined(op1, op2): [op1, op2].map {handleOperation($0)}
}
}
```

Source (Stackoverflow)