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.
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.
You can change the constraint on your extension from T: FloatingPoint to T == Double so you can use the - operator directly.
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).