Operator Overloading
Swift 4.1, Xcode 9.3
I am trying to make a quadratic equation function in Swift.
While working on this, I found that I needed to overload some operators so that I could work with tuples alongside other numbers (Double
in this case), this is because I needed to use my custom ±
operator. Despite the fact that I was only working with value of type Double
in my quadratic function, I decided that I wanted to use generics to make my overloaded operators more flexible for future use.
But–for a reason I don't understand–I am receiving errors regarding the declaration of the overloaded /
operator.
Custom ±
Operator - Working
infix operator ± : AdditionPrecedence
public func ± <T: Numeric>(left: T, right: T) -> (T, T) {
return (left + right, left - right)
}
Quadratic Function - Working
func quadratic(a: Double, b: Double, c: Double) -> (Double, Double) {
return (-b ± sqrt((b * b) - (4 * a * c))) / (2 * a)
}
Overloaded Operators - Partially Working¹
//Binary operator '/' cannot be applied to two 'T' operands
func / <T: Numeric>(lhs: (T, T), rhs: T) -> (T, T) {
return (lhs.0 / rhs, lhs.1 / rhs)
}
func * <T: Numeric>(lhs: (T, T), rhs: T) -> (T, T) {
return (lhs.0 * rhs, lhs.1 * rhs)
}
func - <T: Numeric>(lhs: (T, T), rhs: T) -> (T, T) {
return (lhs.0 - rhs, lhs.1 - rhs)
}
func + <T: Numeric>(lhs: (T, T), rhs: T) -> (T, T) {
return (lhs.0 + rhs, lhs.1 + rhs)
}
//Binary operator '/' cannot be applied to two 'T' operands
func / <T: Numeric>(lhs: T, rhs: (T, T)) -> (T, T) {
return (lhs / rhs.0, lhs / rhs.1)
}
func * <T: Numeric>(lhs: T, rhs: (T, T)) -> (T, T) {
return (lhs * rhs.0, lhs * rhs.1)
}
func - <T: Numeric>(lhs: T, rhs: (T, T)) -> (T, T) {
return (lhs - rhs.0, lhs - rhs.1)
}
func + <T: Numeric>(lhs: T, rhs: (T, T)) -> (T, T) {
return (lhs + rhs.0, lhs + rhs.1)
}
1. I only receive these errors with the /
operator, not with any of the other overloaded operators (+
, -
, or *
).
Overloaded Operators With Errors (/
s) - Not Working
//Binary operator '/' cannot be applied to two 'T' operands
func / <T: Numeric>(lhs: (T, T), rhs: T) -> (T, T) {
return (lhs.0 / rhs, lhs.1 / rhs)
}
//Binary operator '/' cannot be applied to two 'T' operands
func / <T: Numeric>(lhs: T, rhs: (T, T)) -> (T, T) {
return (lhs / rhs.0, lhs / rhs.1)
}
Hypothesis: I think that the fact that I am using the operator /
within the declaration of the overloaded /
operator itself–despite the fact that it is being used in a different context–is causing the error.
Final Question:
How do I resolve the errors while still maintaining the flexibility of my overloaded operators?
Bonus Question 1: If I can (I think that I would probably have to return a String
to accomplish this), I would also like to make a separate quadratic function that can return an exact solution?
Bonus Question 2: Also if anyone knows how to make a separate function that can solve a cubic equation rather than quadratic, that would be appreciated too.