2014-06-19 62 views
3

當重載運算符爲自定義類時,有什麼方法可以覆蓋運算符優先級?在我的例子中,+應該比*更高的優先級。我可以覆蓋默認的運算符優先級嗎?在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 
+0

我並不完全明白你的問題。如果你的意思是,先做一件事,然後做第二件事,你可以使用括號。請澄清你的問題,如果我的回答沒有幫助。 – elito25

+3

也許你可以,但它會讓你的代碼更難閱讀,對吧?因爲每個人都有一個先入爲主的觀點,認爲*的優先級高於+。 –

+1

運算符優先級只能在全局範圍內覆蓋,這意味着哇,這不是一個好主意。 –

回答

6

嗯。它實際上似乎可以。

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

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

但據我所知,這隻能在「文件範圍內」進行,至少根據包括這個類中產生一個編譯器錯誤。

'操作符'只能在文件範圍內聲明。

+0

你能解釋一下數字嗎? – Mohsen

+1

但是,這將適用於全球,而不僅僅是特定的超載,不是嗎? – Chuck

+0

@Mohsen我基本上是隨機選擇它們的。我只提出140個,因爲蘋果在他們的書中用了一個例子,而30則僅僅是因爲它是...呃...更少。如果未指定,則默認值爲100。 –

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 
+0

可在此處找到優先級別:https://developer.apple.com/library/prerelease/ios/文檔/夫特/參考/ Swift_StandardLibrary_Operators/index.html中#// apple_ref/DOC/UID/TP40016054 – par