Hello. I'm running following code and output is a bit surprising for me:
class Foo: Hashable {
var bar: String
init(bar: String) {
self.bar = bar
}
static func == (lhs: Foo, rhs: Foo) -> Bool {
return lhs.bar == rhs.bar
}
func hash(into hasher: inout Hasher) {
hasher.combine(bar)
}
}
let value = 123
let foo = Foo(bar: "bar")
var dictionary = [Foo: Int]()
dictionary[foo] = value
foo.bar = "baz"
if dictionary[foo] == value {
print("wat")
} else {
print("WAT")
}
Sometimes it outputs "wat" and sometimes "WAT". I looked into Dictionary
sources to try and understand why the output may be different and found that it may be something with resizing and re-creating hashtable but I'd like to get some feedback from someone who has more experience with Dictionary
implementation details.
My questions are:
- is this the expected behavior?
- if yes then why?
- if no then what is the expected behavior?