简体   繁体   English

Swift:比较泛型类中的泛型类型

[英]Swift: Compare generic Types in generic class

I'm creating a Matrix class in swift, which I want it to be Generic, so I can use it Like this: 我正在迅速创建一个Matrix类,我希望它是泛型的,因此可以像这样使用它:

let matrix: Matrix<Character>; // Or any other type

I created my class like this: 我创建了这样的课程:

class Matrix<Template>: NSObject {}

I am crating a function that Apply Gravity to matrix that takes an emptyKey of type Template, and drags every element not equal to emptyKey to the bottom of the matrix 我正在创建一个将重力应用到矩阵的函数,该函数采用Template类型的emptyKey,并将不等于emptyKey的每个元素拖到矩阵的底部

// For example emptyKey is "_" and Template is String.

1 _ 2               1 _ _
3 4 5   == To ==>   3 _ 2
6 _ _               6 4 5

The problem is: when I am trying to compare the value in matrix at a specific location which of type Template with the emptyKey which also of type Template , it fails to compile and gave me the error: 问题是:当我试图在特定位置比较矩阵类型中的value ,该位置的类型为Template ,而emptyKey的类型也为Template ,它无法编译,并给了我错误:

Binary operator '==' cannot be applied to two 'Template?' operands

I am using xcode 7.3.1 with Swift 2.2 我在Swift 2.2使用xcode 7.3.1

You need to constrain Template to Equatable. 您需要将模板限制为等于。

class Matrix<Template:Equatable> ...

(Also I would advise that you avoid Optionals. I don't know where you're using them, but your error message suggests that you are, and they are going to get in your way.) (另外,我建议您避免使用Optionals。我不知道您在哪里使用它们,但是您的错误消息表明您在使用Optional,并且它们会妨碍您的使用。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM