AbdulHadi Yasin AbdulHadi Yasin - 4 months ago 18
Swift Question

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:

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

// 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:

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


I am using
xcode 7.3.1
with
Swift 2.2

Answer

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.)

Comments