簡體   English   中英

如何快速重載賦值運算符

[英]how to overload an assignment operator in swift

我想覆蓋 CGFloat 的 '=' 運算符,如下所示:

func = (inout left: CGFloat, right: Float) {
    left=CGFloat(right)
}

所以我可以做到以下幾點:

var A:CGFloat=1
var B:Float=2
A=B

這能做到嗎? 我收到錯誤Explicitly discard the result of the closure by assigning to '_'

這是不可能的 - 如文檔中所述:

不可能重載默認賦值運算符 (=)。 只有復合賦值運算符可以重載。 同樣,三元條件運算符 (a ? b : c) 不能重載。

如果這不能說服您,只需將運算符更改為+=

func +=(left: inout CGFloat, right: Float) {
    left += CGFloat(right)
}

你會注意到你將不再收到編譯錯誤。

誤導性錯誤消息的原因可能是因為編譯器將您的重載嘗試解釋為賦值

您不能覆蓋分配,但可以在您的情況下使用不同的運算符。 例如&=運算符。

func &= (inout left: CGFloat, right: Float) {
    left = CGFloat(right)
}

因此,您可以執行以下操作:

var A: CGFLoat = 1
var B: Float = 2
A &= B

順便說一下,運算符&+&-&*存在於 swift 中。 它們代表無溢出的 C 風格操作。 更多的

這不是operator loading方法。 但結果可能是你所期待的

// Conform to `ExpressibleByIntegerLiteral` and implement it
extension String: ExpressibleByIntegerLiteral {
    public init(integerLiteral value: Int) {
        // String has an initializer that takes an Int, we can use that to
        // create a string
        self = String(value)
    }
}

extension Int: ExpressibleByStringLiteral {
    public init(stringLiteral value: String) {
        self = Int(value) ?? 0
    }
}

// No error, s2 is the string "4"
let s1: Int = "1"
let s2: String = 2

print(s1)
print(s2)
print(s1 + 2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM