Generic Operator Overloading in Swift

对着背影说爱祢 提交于 2019-12-25 01:57:59

问题


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:


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 
}


来源:https://stackoverflow.com/questions/28739567/generic-operator-overloading-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!