Given an array of instances of a `Hashable` value type, all equal according to `Equatable` protocol, but with distinct `hashValue`s, I would expect that initialising a set with that array would preserve all the instances. Instead, running the code below in an iOS playground on Xcode 8.0 (8A218a), results in a behaviour that I cannot explain. If anyone can, I’d be very grateful!
struct X: Hashable {
let x: Int
let hashValue: Int
Equal hashables must have the same hashValue. If you violate this rule,
all bets are off. As the doc says:
A hash value, provided by a type's hashValue property, is an integer
that is the same for any two instances that compare equally. That is,
for two instances a and b of the same type, if a == b then a.hashValue
== b.hashValue.
···
on Sun Oct 23 2016, milos <swift-users-AT-swift.org> wrote:
Given an array of instances of a `Hashable` value type, all equal
according to `Equatable` protocol, but with distinct `hashValue`s,
Apple says this: “A hash value, provided by a type’s hashValue property, is an integer that is the same for any two instances that compare equally.”
You violated this rule in the original example.
Apple says: “Set and dictionary performance depends on hash values that minimize collisions for their associated element and key types, respectively.”
From which I draw the conclusion that there are “under the hood” optimizations at work that produce the results in your example. These can probably change from compiler version to compiler version and are principally unreliable because your example violated the rule for Hashable.
Rien.
···
On 23 Oct 2016, at 10:51, milos via swift-users <swift-users@swift.org> wrote:
Given an array of instances of a `Hashable` value type, all equal according to `Equatable` protocol, but with distinct `hashValue`s, I would expect that initialising a set with that array would preserve all the instances. Instead, running the code below in an iOS playground on Xcode 8.0 (8A218a), results in a behaviour that I cannot explain. If anyone can, I’d be very grateful!
struct X: Hashable {
let x: Int
let hashValue: Int