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

前端 未结 1 1829
灰色年华
灰色年华 2021-01-11 23:07

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 fun         


        
相关标签:
1条回答
  • 2021-01-11 23:37

    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
    

    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
    }
    

    Therefore the following expression:

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

    will be evaluated as:

    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.

    0 讨论(0)
提交回复
热议问题