Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type "T?" does not conform to protocol 'Equatable'

Tags:

swift

I have a generic class similar to this one:

class C<T: Equatable> {

    let t: T

    init(t: T) { 
        self.t = t
    }

}

When I try to wrap Int? inside, I get the following error:

// ERROR: Type "Int?" does not conform to protocol 'Equatable'
let c = C<Int?>(t: nil)

A quick test shows that Int? indeed is Equatable:

let a: Int? = 5
let b: Int? = 6

let c = a == b // NO ERROR

Maybe I'm just too tired today?

like image 498
Rudolf Adamkovič Avatar asked Apr 16 '26 02:04

Rudolf Adamkovič


1 Answers

Int? is NOT Equatable

You required T to be Equatable.

But you are passing Int? (a shorthand notation for Optional<Int>) which is not Equatable.

Declaration of Optional

You can verify it looking at the source declaration of Optional

public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible

There is no Equatable. Even _Reflectable and NilLiteralConvertible are NOT Equatable.

Your test

So why does your test seem to prove that Int? is indeed Equatable?

let a: Int? = 5
let b: Int? = 6

let c = a == b // NO ERROR

Actually this does not mean that Int? is Equatable. Infact you are invoking this function

public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool

as you can see the function requires T to be Equatable. And since T and T? are totally different types, this does not mean that T? is Equatable as well.

like image 157
Luca Angeletti Avatar answered Apr 17 '26 16:04

Luca Angeletti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!