Operators in Protocols

Lets say you create a vector class that uses Numeric for T.

struct Vector2D<T: Numeric> {
   var x : T
   var y : T

}

You may want the following operator

extension Vector2D<T> {
    static public prefix func -(vector : inout Vector2D<T>) {
       // doesn't work . Cannot convert value of type 'T' to expected argument type 'inout Vector2D<_>'
       vector.x = -vector.x
       vector.y = -vector.y
       // and this doesn't work because of the same error.
       // vector = Vector2D.init(x: -vector.x, y: -vector.y)
    }
}

I know I can just multiply by -1 and have it work but I'm curious to know why the way I tried to do it doesn't work even though Numeric has the additive inverse operand .

Numeric does not have a unary minus operator. Did you mean SignedNumeric instead?

sorry. I didnt read properly. you are correct.

Terms of Service

Privacy Policy

Cookie Policy