Hi all,
I am playing around with this sample code inside a Playground:
import Foundation
struct Operation: Hashable {
let subject: String
let type: OperationType
init(subject: String, type: OperationType) {
self.subject = subject
self.type = type
}
static func == (lhs: Operation, rhs: Operation) -> Bool {
lhs.subject == rhs.subject
}
enum OperationType: Hashable {
case insert
case update
case delete
}
}
var pendingOperations: Set<Operation> = []
let insertSubject1 = Operation(subject: "1", type: .insert)
insertSubject1.hashValue
let updateSubject1 = Operation(subject: "1", type: .update)
updateSubject1.hashValue
insertSubject1 == updateSubject1
pendingOperations.insert(insertSubject1)
pendingOperations.count
pendingOperations.insert(updateSubject1)
pendingOperations.count
and I noticed that sometimes the second insertion succeed (returning (inserted: true, memberAfterInsert: Operation)
) and sometimes not.
If I remove the explicit Equatable
conformance, or I define it in a more appropriate way like:
static func == (lhs: Operation, rhs: Operation) -> Bool {
lhs.subject == rhs.subject && lhs.type == rhs.type
}
the second insertion always succeed as expected.
This led up to my questions:
-
Why is the behavior inconsistent when
Equatable
considers only a subset of the properties considered byHashable
? -
What is the role of
Equatable
and why is apparently not always honoured?