乘法符号的定义是这样的。
public func *(lhs: Int, rhs: Int) -> Int
我可以像这样在函数中使用它。
func productUsingReduce(xs: [Int]) -> Int {
return xs.reduce(1, { x,y in x * y})
}
或者只是像这样。
func productUsingReduce(xs: [Int]) -> Int {
return xs.reduce(1, *)
}
如果我尝试用不同的名称定义相同的东西。
func yes(lhs: Int, rhs: Int) -> Int {
return lhs * rhs
}
当我尝试像这样使用它时出现编译器错误。
func productUsingReduce(xs: [Int]) -> Int {
return xs.reduce(1, { x,y in x yes y})
}
为什么?
为什么下面的语法不能编译?
func productUsingReduce(xs: [Int]) -> Int {
return xs.reduce(1, { x, y in *(lhs: x, rhs: y) })
}
最佳答案
您的函数 func yes(..
只是一个标准函数。
要定义一个操作符你必须声明操作符
infix operator yes
以及对应的函数
func yes(lhs: Int, rhs: Int) -> Int {
return lhs * rhs
}
但坏消息来了:您不能将字母数字字符用作运算符。
关于swift - 关于函数,数学符号函数 * 的调用方式不同。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40503721/