Swift中的运算符优先级重载

时间:2014-06-19 21:57:42

标签: swift

在重载自定义类的运算符时,有没有办法覆盖运算符优先级?在我的示例中,+应优先于*。我可以覆盖默认的运算符优先级吗?

class Vector{
    var x:Int
    var y:Int
    init(x _x:Int, y _y:Int){
        self.x = _x
        self.y = _y
    }
}

func *(lhs:Vector, rhs:Vector)->Int{
    return lhs.x * rhs.y + rhs.x + rhs.y
}

func +(lhs:Vector, rhs:Vector)->Vector{
    return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}

var v1 = Vector(x: 6, y: 1)
var v2 = Vector(x: 3, y: 1)


v1 * v2 + v1

2 个答案:

答案 0 :(得分:6)

嗯。它实际上似乎你可以。

operator infix + { associativity left precedence 140 }
operator infix * { associativity left precedence 30 }

let x = 3 + 4 * 5 // outputs 35

但据我所知,这只能在“文件范围”完成,至少根据在类中包含它所产生的编译器错误。

  

'operator'只能在文件范围内声明。

答案 1 :(得分:5)

回答@Mohsen的问题

来自公开发布的文档here,并且合理使用:

Exponentiative (No associativity, precedence level 160)
        << Bitwise left shift
        >> Bitwise right shift

Multiplicative (Left associative, precedence level 150)
        * Multiply
        / Divide
        % Remainder
        &* Multiply, ignoring overflow
        &/ Divide, ignoring overflow
        &% Remainder, ignoring overflow
        & Bitwise AND

Additive (Left associative, precedence level 140)
        + Add
        - Subtract
        &+ Add with overflow
        &- Subtract with overflow
        | Bitwise OR
        ^ Bitwise XOR

Range (No associativity, precedence level 135)
        ..< Half-open range
        ... Closed range

Cast (No associativity, precedence level 132)
        is Type check
        as Type cast

Comparative (No associativity, precedence level 130)
        < Less than
        <= Less than or equal
        > Greater than
        >= Greater than or equal
        == Equal
        != Not equal
        === Identical
        !== Not identical
        ~= Pattern match

Conjunctive (Left associative, precedence level 120)
        && Logical AND

Disjunctive (Left associative, precedence level 110)
        || Logical OR

Ternary Conditional (Right associative, precedence level 100)
        ?: Ternary conditional

Assignment (Right associative, precedence level 90)
        = Assign
        *= Multiply and assign
        /= Divide and assign
        %= Remainder and assign
        += Add and assign
        -= Subtract and assign
        <<= Left bit shift and assign
        >>= Right bit shift and assign
        &= Bitwise AND and assign
        ^= Bitwise XOR and assign
        |= Bitwise OR and assign
        &&= Logical AND and assign
        ||= Logical OR and assign