如何在 Swift 3 中声明具有新优先级组的 exponent/power 运算符?

How to declare exponent/power operator with new precedencegroup in Swift 3?

Swift 3 for Xcode 8 beta 6 发生了变化,现在我无法像以前那样声明我的操作员的权力:

infix operator ^^ { }
public func ^^ (radix: Double, power: Double) -> Double {
    return pow((radix), (power))
}

我已经阅读了一些相关内容并且有一个新的变化 been introduced in Xcode 8 beta 6

据此我猜我必须声明一个优先级组并将其用于我的运算符,如下所示:

precedencegroup ExponentiativePrecedence {}

infix operator ^^: ExponentiativePrecedence
public func ^^ (radix: Double, power: Double) -> Double {
    return pow((radix), (power))
}

我的方向是否正确?优先组的{}里面应该放什么?

我的最终目标是能够在swift中使用简单的运算符进行幂运算,例如:

10 ^^ -12
10 ^^ -24

您的代码已经编译并运行 - 如果您只是单独使用运算符,则无需定义优先关系或关联性,例如您给出的示例:

10 ^^ -12
10 ^^ -24

但是,如果您想与其他运算符一起工作,以及将多个指数链接在一起,您需要定义一个优先关系 higher than the MultiplicationPrecedence and a right associativity

precedencegroup ExponentiativePrecedence {
    associativity: right
    higherThan: MultiplicationPrecedence
}

因此表达式如下:

let x = 2 + 10 * 5 ^^ 2 ^^ 3

将被评估为:

let x = 2 + (10 * (5 ^^ (2 ^^ 3)))
//          ^^    ^^    ^^--- Right associativity
//          ||     \--------- ExponentiativePrecedence > MultiplicationPrecedence
//           \--------------- MultiplicationPrecedence > AdditionPrecedence,
//                            as defined by the standard library

标准库优先级组的完整列表可在 the evolution proposal 上找到。