Error: binary operator '-' cannot be applied to operands of type 'T' and 'Double'

Hi

Any idea how to get rid of the error message in the subject?
Foo works as a function but not as a method.
I want to keep A non-generic.

Thanks.

class A {
        var x: Double = 1.0
}

class B<T> {
        init(y: T) {
                self.y = y
        }
        var y: T
}

typealias Bd = B<Double>

func foo(b: Bd, a: A) {
        _ = b.y - a.x // works
}

extension B where T: FloatingPoint {
        func foo(a: A) {
                _ = y - a.x // doesn't work
        }
}

Arithmetic operations are defined to accept Self. So you can’t subtract a Double from some arbitrary type conforming to FloatingPoint. You have to guarantee the operands have the same type.

Thanks.

I tried something like

extension B where T: Double {}

but that didn’t work either. Any ideas?

Your function works because B.T is known to be Double at that point. In your extension, B.T can be any type conforming to FloatingPoint, and Swift does not allow mixing multiple numeric types with mathematical operators.

You have multiple options.

  1. You can change the constraint on your extension from T: FloatingPoint to T == Double so you can use the - operator directly.
  2. You could also change it to T: BinaryFloatingPoint, which gives you access to BinaryFloatingPoint.init(_ value: Double), although you should be aware that this will round the double from your A to fit into whatever floating point type B is specialized with is. You would then use y - T.init(a.x).
1 Like

Double is a struct, you can’t inherit from it. @ahti listed some valid approaches for you.

T == Double

Ahhh, thanks. Missed that.
Guess it’s late here in Europe. :)

1 Like