Skip to content

Instantly share code, notes, and snippets.

@chakrit
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chakrit/be30f1f8415e3fbf83df to your computer and use it in GitHub Desktop.
Save chakrit/be30f1f8415e3fbf83df to your computer and use it in GitHub Desktop.
Defining functions `==` on a protocol or generically on a protocol does not quiet work. The difference between the 3 versions is in where `Equatable` is applied and how `==` is defined.
import Foundation
import XCPlayground
protocol Identifiable: Hashable {
var id: String { get }
}
@objc class IdentifiableObject: NSObject, Identifiable {
private let _id: String
var id: String { return _id }
override var hashValue: Int { return id.hashValue }
init(id: String) {
_id = id
super.init()
}
}
extension IdentifiableObject: Equatable { }
func ==<T: IdentifiableObject>(lhs: T, rhs: T) -> Bool {
return lhs.id == rhs.id
}
// MODELS
class A: IdentifiableObject { }
class B: IdentifiableObject { }
let a = A(id: "equal")
let b = B(id: "equal")
func check<T: Identifiable>(lhs: T, rhs: T) -> Bool {
return lhs == rhs
}
dump(a == b) // <------------- FALSE
dump(check(a, b)) // <------------- TRUE
import Foundation
import XCPlayground
protocol Identifiable: Hashable {
var id: String { get }
}
@objc class IdentifiableObject: NSObject, Identifiable {
private let _id: String
var id: String { return _id }
override var hashValue: Int { return id.hashValue }
init(id: String) {
_id = id
super.init()
}
}
extension IdentifiableObject: Equatable { }
func ==(lhs: IdentifiableObject, rhs: IdentifiableObject) -> Bool {
return lhs.id == rhs.id
}
// MODELS
class A: IdentifiableObject { }
class B: IdentifiableObject { }
let a = A(id: "equal")
let b = B(id: "equal")
func check<T: Identifiable>(lhs: T, rhs: T) -> Bool {
return lhs == rhs
}
dump(a == b) // <------------- TRUE
dump(check(a, b)) // <------------- TRUE
import Foundation
import XCPlayground
protocol Identifiable: Hashable, Equatable {
var id: String { get }
}
@objc class IdentifiableObject: NSObject, Identifiable {
private let _id: String
var id: String { return _id }
override var hashValue: Int { return id.hashValue }
init(id: String) {
_id = id
super.init()
}
}
func ==<T: Identifiable>(lhs: T, rhs: T) -> Bool {
return lhs.id == rhs.id
}
// MODELS
class A: IdentifiableObject { }
class B: IdentifiableObject { }
let a = A(id: "equal")
let b = B(id: "equal")
func check<T: Identifiable>(lhs: T, rhs: T) -> Bool {
return lhs == rhs
}
dump(a == b) // <------------- FALSE
dump(check(a, b)) // <------------- TRUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment