There is an interesting discussion going on here in this pitch: [Pitch] Default implementation of Hashable for AnyObject.
When playing with the example code posted by @mbrandonw, I noticed something unusual: nondeterministic program behaviour.
// it.swift
import Foundation
@main
enum Driver {
static func main() async throws {
hash_my_class ()
}
}
// [https://forums.swift.org/t/pitch-default-implementation-of-hashable-for-anyobject/88853/9]
//
class MyClass: Hashable {
var i: Int
init(i: Int) {
self.i = i
}
static func == (lhs: MyClass, rhs: MyClass) -> Bool { lhs.i == rhs.i }
func hash (into hasher: inout Hasher) {
hasher.combine(i)
}
}
func hash_my_class() {
print (#function, "...")
var dictionary: [MyClass: Bool] = [:]
let object = MyClass (i: 0)
dictionary [object] = true
object.i = 1
dictionary [object] = false
// 🛑 Fatal error: Duplicate keys of type 'MyObject' were found in a Dictionary.
print (#function, "finished")
}
When I build and run it from the command line (also in Xcode (Version 26.5 (17F42))), I get the following nondeterministic result: the program sometimes crashes and sometimes doesn't.
> swiftc -parse-as-library it.swift
> ./it
hash_my_class() ...
Fatal error: Duplicate keys of type 'MyClass' were found in a Dictionary.
This usually means either that the type violates Hashable's requirements, or
that members of such a dictionary were mutated after insertion.
Trace/BPT trap
> ./it
hash_my_class() ...
hash_my_class() finished
> ./it
hash_my_class() ...
Fatal error: Duplicate keys of type 'MyClass' were found in a Dictionary.
This usually means either that the type violates Hashable's requirements, or
that members of such a dictionary were mutated after insertion.
Trace/BPT trap
> ./it
hash_my_class() ...
hash_my_class() finished
> ./it
hash_my_class() ...
Fatal error: Duplicate keys of type 'MyClass' were found in a Dictionary.
This usually means either that the type violates Hashable's requirements, or
that members of such a dictionary were mutated after insertion.
Trace/BPT trap
> ./it
hash_my_class() ...
hash_my_class() finished
> ./it
hash_my_class() ...
Fatal error: Duplicate keys of type 'MyClass' were found in a Dictionary.
This usually means either that the type violates Hashable's requirements, or
that members of such a dictionary were mutated after insertion.
Trace/BPT trap
Why this nondeterministic behaviour?