问题描述
Swift 3中针对Xcode 8 beta 6进行了更改,现在我无法像以前一样声明我的运算符的威力:
There's been a change in Swift 3 for Xcode 8 beta 6 and now I'm not able to declare my operator for power as I did before:
infix operator ^^ { }
public func ^^ (radix: Double, power: Double) -> Double {
return pow((radix), (power))
}
我已经阅读了一下,并且有了新的变化在Xcode 8 beta 6中引入
I've read a bit about it and there's a new change been introduced in Xcode 8 beta 6
据此,我猜测我必须声明一个优先级组并将其用于我的运算符,如下所示:
From this I'm guessing I have to declare a precedence group and use it for my operator like this:
precedencegroup ExponentiativePrecedence {}
infix operator ^^: ExponentiativePrecedence
public func ^^ (radix: Double, power: Double) -> Double {
return pow((radix), (power))
}
我要朝正确的方向努力吗?我应该在优先级组的{}中放入什么?
Am I going in the right direction to make this work? What should I put inside the {} of the precedence group?
我的最终目标是能够通过简单的操作员迅速进行电源操作,例如:
My final aim is to be able to make power operations with a simple operator in swift, e.g.:
10 ^^ -12
10 ^^ -24
推荐答案
您的代码已经编译并运行-如果您只是单独使用运算符,则无需定义优先级关系或关联性,例如在您给出的示例中:
Your code already compiles and runs – you don't need to define a precedence relationship or an associativity if you're simply using the operator in isolation, such as in the example you gave:
10 ^^ -12
10 ^^ -24
但是,如果您想与其他运算符一起使用,并且将多个指数链接在一起,则需要定义一个优先级关系,该优先级关系为 MultiplicationPrecedence
和正确的关联性.
However, if you want to work with other operators, as well as chaining together multiple exponents, you'll want to define a precedence relationship that's 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 full list of standard library precedence groups is available on the evolution proposal.
这篇关于如何在Swift 3中使用新的优先级组声明指数/幂运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!