【问题标题】:Regarding functions, the math symbol function * is called differently. Why?关于函数,数学符号函数 * 的调用方式不同。为什么?
【发布时间】:2016-11-09 09:36:03
【问题描述】:

乘法符号的定义是这样的。

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})
}

为什么?

为什么下面的 sytnax 不能编译?

func productUsingReduce(xs: [Int]) -> Int {
    return xs.reduce(1, { x, y in *(lhs: x, rhs: y) })
}

【问题讨论】:

    标签: swift function syntax


    【解决方案1】:

    您的函数func yes(.. 只是一个标准函数。

    要定义运算符,您必须声明运算符

    infix operator yes
    

    以及对应的功能

    func yes(lhs: Int, rhs: Int) -> Int {
       return lhs * rhs
    }
    

    但现在坏消息来了:您不能使用字母数字字符作为运算符。

    【讨论】:

      【解决方案2】:

      * 定义由两部分组成:

      方法定义(在Swift.Math.IntegersSwift.Math.Floating等)

      public func *(lhs: Int, rhs: Int) -> Int
      

      及其操作符行为(在Swift中,你可以在Xcode和CMD中写import Swift+点击它来访问文件)

      infix operator * : MultiplicationPrecedence
      

      最后一个 sn-p 使* 成为中缀运算符,因此您只能以中缀形式使用它。


      关于你的yes 函数,你不能让它表现得像一个运算符。虽然您可以定义自己的自定义运算符,但它们只能包含某些字符。根据language specification

      自定义运算符可以以 ASCII 字符 /、=、-、+、!、*、%、、&、|、^、? 或 ~ 之一或在下面的语法(其中包括来自数学运算符、杂项符号和 Dingbats Unicode 块等的字符)。在第一个字符之后,也允许组合 Unicode 字符。

      所以你必须使用它的标准函数形式。

      但你可以这样做

      func ^^^(lhs: Int, rhs: Int) -> Int {
        return lhs * rhs
      }
      
      infix operator ^^^
      

      这将按预期工作

      3 ^^^ 2 // 6
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-04
        • 2017-05-29
        • 1970-01-01
        • 2013-04-08
        • 1970-01-01
        • 2018-09-20
        • 2012-01-10
        • 1970-01-01
        相关资源
        最近更新 更多