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

gbd*_*vid 9 operator-precedence swift swift3 xcode8-beta6

对于Xcode 8 beta 6,Swift 3已经发生了变化,现在我无法像以前那样申报操作员的电源:

infix operator ^^ { }
public func ^^ (radix: Double, power: Double) -> Double {
    return pow((radix), (power))
}
Run Code Online (Sandbox Code Playgroud)

我已经读过一些关于它的内容,并且在Xcode 8 beta 6中引入了一个新的变化

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

precedencegroup ExponentiativePrecedence {}

infix operator ^^: ExponentiativePrecedence
public func ^^ (radix: Double, power: Double) -> Double {
    return pow((radix), (power))
}
Run Code Online (Sandbox Code Playgroud)

我是否朝着正确的方向努力使这项工作成功?我应该把什么放在优先组的{}里面?

我的最终目标是能够使用简单的操作员快速进行动力操作,例如:

10 ^^ -12
10 ^^ -24
Run Code Online (Sandbox Code Playgroud)

Ham*_*ish 10

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

10 ^^ -12
10 ^^ -24
Run Code Online (Sandbox Code Playgroud)

但是,如果你想与其他运营商合作,以及多个指数串联起来,你要定义一个优先级的关系那是高于MultiplicationPrecedence一个右结合.

precedencegroup ExponentiativePrecedence {
    associativity: right
    higherThan: MultiplicationPrecedence
}
Run Code Online (Sandbox Code Playgroud)

因此以下表达式:

let x = 2 + 10 * 5 ^^ 2 ^^ 3
Run Code Online (Sandbox Code Playgroud)

将被评估为:

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

进化建议中提供了标准库优先级组的完整列表.