General operator overload in Swift

I study Swift and wonder about using Generics with operator overloading. This is my requirement:

  • You have a basic general structure that implements universal matrix functionality that has three main parameters: row: Int, column: Int and array: [T].
  • It is required to execute the operator ==, i.e. each parameter ==.
  • No need to duplicate operator overload functions for each type.

It seems that Swift is not smart enough to allow me to write a generic operator overload function that references a common array [T] without any workarounds?

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

I was just wondering, what is the general consensus among professionals here? Sorry, I will send the sample code as an edit soon.

Floor

0
source share
1 answer

Here is how you can do it. It is very simple, you just need to make sure that T is equivalent.

struct Matrix<T> {
    // Definition goes here.
    var array = [T]()
}
func ==<T: Equatable>(lhs: Matrix<T>, rhs: Matrix<T>) -> Bool {
    return lhs.array == rhs.array 
}
+1
source

Source: https://habr.com/ru/post/1618081/


All Articles