我正在尝试了解有关递归枚举的更多信息。
这是我的代码:
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)
}
我如何一个接一个地执行plus
然后squareRoot
操作?
我一直收到这个错误:
无法调用非功能类型的值(操作,操作)
答案 0 :(得分:1)
使用.Unary
和.Binary
,你做得对。您正在检索功能并执行它们。
然而,对于.Combined
,您正在检索操作元组并将其用作函数。你应该做的是检索元组中的函数并执行它们。
您可以使用递归函数代替您的开关,如下所示:
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)
}
}