[swift-users] Type "T?" does not conform to protocol 'Equatable'

Peter Vertes pvertes at gmail.com
Mon Feb 29 09:33:02 CST 2016


To extend on Keith’s explanation:

class C<T: Equatable> {
    let t: T?
    init(t: T?) { self.t = t }
}

let a = C<Int>(t: nil)
print(a.t)

let b = C<Int>(t: 5)
print(b.t)

let c = C<Int>(t: 5)
print(c.t)

func ==(lhs: C<Int>, rhs: C<Int>) -> Bool {
    return lhs.t == rhs.t
}

var d = a == b	// false
var e = b == c	// true

You’d also need to override the “==“ operator for C<Int> types in order to be able to compare them.

-Pete



> On Feb 29, 2016, at 10:07 AM, Keith Duvall via swift-users <swift-users at swift.org> wrote:
> 
> Don’t mark it as optional in the generic definition. Mark it as optional in your implementation.
> 
> class C<T: Equatable> {
> 	let t: T?
> 	init(t: T?) {
> 		self.t = t
> 	}
> }
> 
> let a = C<Int>(t: nil)
> 
> print(a.t) // nil
> 
> let b = C<Int>(t: 5)
> 
> print(b.t) // Optional(5)
> 
> Keith
> 
> 
>> On Feb 29, 2016, at 9:24 AM, Rudolf Adamkovič via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> wrote:
>> 
>> Hi everyone!
>> 
>> I have a generic class similar to this one:
>> 
>> class C<T: Equatable> {
>>     let t: T
>>     init(t: T) { self.t = t }
>> }
>> 
>> When try to wrap ‘Int?' inside, I get the following error:
>> 
>> let a = C<Int?>(t: nil) // ERROR: Type "Int?" does not conform to protocol 'Equatable'
>> 
>> Yet when I try to compare two ‘Int?’ values, everything works:
>> 
>> let a: Int? = 5
>> let b: Int? = 6
>> 
>> let c = a == b // NO ERROR
>> 
>> So, is ‘Int?' equatable or not?
>> 
>> Thanks!
>> 
>> R+
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org <mailto:swift-users at swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160229/5b5e7cd5/attachment.html>


More information about the swift-users mailing list