0

I've been learning Swift and have a question about using Generics with Operator Overloading. This is my requirement:

  1. Have a basic generic struct that implements generic matrix functionality, having three main parameters: row:Int, column:Int and array:[T].
  2. Want to implement == operator, i.e. each parameter is ==.
  3. Don't want to have to duplicate operator overload functions for each type.

It seems Swift isn't smart enough to allow me to write a generic operator overload function that references the generic array [T] without some workarounds?

I have read this post: [http://www.raywenderlich.com/80818/operator-overloading-in-swift-tutorial][1] and the solution given there seems surprisingly complicated.

I just wondered what the general consensus amongst the pro's here is? Sorry, I will post a code sample as an edit shortly.

Paul

1
  • So where's that code sample? lol... Commented May 6, 2015 at 21:26

1 Answer 1

2

Here's how you can do that. Its very easy, you just need to ensure that T is Equatable.

struct Matrix<T> {
    // Definition goes here.
    var array = [T]()
}
func ==<T: Equatable>(lhs: Matrix<T>, rhs: Matrix<T>) -> Bool {
    return lhs.array == rhs.array 
}
Sign up to request clarification or add additional context in comments.

2 Comments

This currently doesn't work - if either array is empty, true will be returned regardless of whether the other array is empty or not. It would be better to write: return lhs.array == rhs.array.
Sorry I forgot about that my bad

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.