不能使用函数名返回函数

问题描述

我创建了一个操作枚举:

enum Operation {
    case add,subtract,multiply,divide
}

而且我希望每个案例都有其适当的功能

enum Operation {
    case add,divide
    
    var action: (Int,Int) -> Int {
        switch self {
        case .add: 
            return { $0 + $1 }
        case .subtract:
            return { $0 - $1 }
        case .multiply:
            return { $0 * $1 }
        case .divide: 
            return { $0 / $1 }
        }
    }
}

上述代码有效,但也有 +(Int,Int) -> Int-(Int,Int) -> Int*(Int,Int) -> Int/(Int,Int) -> Int函数。为什么不能(或者如果可能的话)我像这样使用它们:

var action: (Int,Int) -> Int {
    switch self {
    case .add: 
        return +
    case .subtract:
        return -
    case .multiply:
        return *
    case .divide: 
        return /
    }
}

如果我添加一个额外的函数并使用它的名字,一切都会正常的:

func foo(_ lhs: Int,_ rhs: Int) -> Int {
    return 0
}

...
case .add:
    return foo
...

但为什么 +-*/ 不起作用?这些也只是函数名称,不是吗?我可以在 .reduce(0,+) 上使用它们,为什么不在这里

这是我得到的错误Unary operator cannot be separated from its operand

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...