2015-05-26 39 views
2

我有一個奇怪的情況,我似乎無法獲得單等於超載超載單的equals迅速

這工作得很好:當我將其更改爲

public func /=<T: ConvertibleUnit>(inout left: T, right: Int) { 
    left.value = (left.value/Double(right)) 
} 

public func =<T: ConvertibleUnit>(inout left: T, right: Int) { 
    left.value = Double(right) 
} 

我得到的錯誤:

符實現withou t匹配的操作員聲明

有什麼瘋狂的明顯我失蹤了嗎?

我玩過中綴,看起來沒有太多。我假設它的解釋=錯了?

+1

我記不得了,但我記得在某處讀過Swift不允許你重載'='操作符。 – NobodyNada

回答

6

沒有骰子,恐怕。從language reference

The tokens =, ->, //, /*, */, ., the prefix operators <, &, and ?, the infix operator ?, and the postfix operators >, !, and ? are reserved. These tokens can’t be overloaded, nor can they be used as custom operators.

相反,如果你想ConvertibleUnit永遠是可創建從Int,給定協議的init(_ val: Int)方法,使人們可以寫let unit = T(42)。或者甚至可以考慮使其符合IntegerLiteralConvertible

通常,Swift中的首選樣式不會在不同類型之間進行自動/隱式轉換。這就是爲什麼,例如,您必須將Int投射到Double,然後才能將其添加到另一個Double

當然,你也可以這樣寫:

func +(lhs: Int, rhs: Double) -> Double { 
    return Double(lhs) + rhs 
} 

let i = 1 
let f = 1.2 
i + f // = 2.2 

但這是一般不被認爲是很好的做法。

3

Apple's official documentation解釋,

It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded.

你可能創建一個使用infix一個新的運營商,但遺憾的是你不能重載「=」。