Overload of single equals in fast
I have a strange situation where I cannot get single values ββfor overload
This works great:
public func /=<T: ConvertibleUnit>(inout left: T, right: Int) {
left.value = (left.value / Double(right))
}
Once I change it to:
public func =<T: ConvertibleUnit>(inout left: T, right: Int) {
left.value = Double(right)
}
I am getting the error:
Implementing an operator without matching the operator declaration
Is there something crazy I'm missing?
I've been playing around with infishes and it doesn't seem like that much. Do I somehow assume that his interpretation is wrong?
source to share
No cubes, I'm afraid. From the reference
Tokens =, β, //, / *, * /,., Prefix operators <, amp ;, and?, Infix operator & and postfix operators>,! and? reserved. These tokens cannot be overloaded and cannot be used as custom operators.
Instead, if you want to ConvertibleUnit
always be created with Int
, give the protocol a method init(_ val: Int)
for people to write let unit = T(42)
. Or perhaps even consider making it fit IntegerLiteralConvertible
.
Generally, the preferred style in Swift should not have automatic / implicit conversion between different types. That's why, for example, you have to overlay Int
on Double
before you can add it on another Double
.
You can of course write things like this:
func +(lhs: Int, rhs: Double) -> Double {
return Double(lhs) + rhs
}
let i = 1
let f = 1.2
i + f // = 2.2
but this is generally not considered good practice.
source to share
As explained in the official Apple documentation ,
Cannot overload the default assignment operator (=). Only complex assignment operators can be overloaded. Likewise, the ternary conditional operator (a? B: c) cannot be overloaded.
You could create a new operator using infix
, but unfortunately, you simply cannot overload '='.
source to share