Swift中的通用运算符重载 [英] Generic Operator Overloading in Swift

查看:77
本文介绍了Swift中的通用运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习Swift,并对使用泛型与操作符重载有个疑问。这是我的要求:

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


  1. 有一个基本的泛型结构实现了泛型矩阵功能,它有三个主要参数:row:Int,column:Int和数组:[T]。

  2. 要实现==运算符,即每个参数都是==。

  3. 不希望为每种类型重复运算符重载函数。
  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.

看起来Swift不够聪明,因此我不能编写通用运算符重载函数引用泛型数组[T]没有一些解决方法?

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?

我已阅读此帖:[ http://www.raywenderlich.com/80818/operator-overloading-in-swift-tutorial] [1] 和给出的解决方案似乎令人惊讶地复杂。

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

推荐答案

以下是你如何做到的。它非常容易,你只需要确保T是Equatable。

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 
}

这篇关于Swift中的通用运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆