private enum Operation {
case BinaryOperation((Double, Double) -> Double)
case UrinaryOperation((Double) -> Double)
}
let plus = Operation.BinaryOperation({$0 + $1})
let minus = Operation.BinaryOperation({$0 - $1})
let multiply = Operation.BinaryOperation({$0 * $1})
let divide = Operation.BinaryOperation({$0 / $1})
plus(3.0,2.0)
但是,我收到以下错误:
MyPlayground.playground:5:13:错误:无法调用非功能类型的值'操作' 加(3.0,2.0) ~~~~ ^
答案 0 :(得分:0)
您尝试执行的操作的正确语法是:
if case let Operation.BinaryOperation(operation) = plus {
operation(3.0, 2.0) // results in 5.0
}
您需要获取枚举的相关值。
请注意,您的闭包可以简化为
let plus = Operation.BinaryOperation(+)
let minus = Operation.BinaryOperation(-)
let multiply = Operation.BinaryOperation(*)
let divide = Operation.BinaryOperation(/)