Hello ! I would like to have some clarifications about why Set does not interact properly with a Hashable struct declared in a function.
Here I have a struct Hello that conforms to hashable and only needs its id for the hashValue. Because structs need to have Equatable custom conformance to have custom hash behavior, so a == function is declared. 23
I first declare a Set with an identifier 123 and the I try to insert another struct having the same identifier with different "value". It does not insert the new element because it is considered as the same by the equality.
struct Hello: Hashable {
let id: Int
let value: String
var hashValue: Int {
return id.hashValue
}
init(id: Int, value: String) {
self.id = id
self.value = value
}
static func == (lhs: Hello, rhs: Hello) -> Bool {
return lhs.id == rhs.id
}
}
func testFunc() {
var set = Set<Hello>([Hello(id: 123, value: "Hello")])
// Set is now `[Hello #1 in __lldb_expr_104.testFunc() -> ()(id: 123, value: "Hello")]`
set.insert(Hello(id: 123, value: "World"))
// Set is still `[Hello #1 in __lldb_expr_104.testFunc() -> ()(id: 123, value: "Hello")]`.
}
testFunc()
Here I have a struct Hello that conforms to hashable and only needs its id for the hashValue and it is declared in a function. The struct is the same as the previous example but it does not work, the set keep inserting it while the id is the same. The custom comparison operand is not used so I suspect that the default implementation is called instead.
func testFunc() {
struct Hello: Hashable {
let id: Int
let value: String
var hashValue: Int {
return id.hashValue
}
init(id: Int, value: String) {
self.id = id
self.value = value
}
static func == (lhs: Hello, rhs: Hello) -> Bool {
return lhs.id == rhs.id
}
}
var set = Set<Hello>([Hello(id: 123, value: "Hello")])
// Set is now `[Hello #1 in __lldb_expr_104.testFunc() -> ()(id: 123, value: "Hello")]`
set.insert(Hello(id: 123, value: "World"))
// Set is now [Hello #1 in __lldb_expr_115.testFunc() -> ()(id: 123, value: "Hello"), Hello #1 in __lldb_expr_115.testFunc() -> ()(id: 123, value: "World")]
}
testFunc()