[swift-users] Equality is broken, isn't it?

Brent Royal-Gordon brent at architechies.com
Wed Jul 6 23:21:15 CDT 2016


> On Jul 6, 2016, at 9:54 AM, Alexey Komnin via swift-users <swift-users at swift.org> wrote:
> 
> Here is the code:
> 
>    let a: String = "abc"
>    let b: NSString = "abc"
> 
>    assert(a == b)
>    assert(a.hashValue == b.hashValue, "a.hashValue(\(a.hashValue)) !=
> b.hashValue(\(b.hashValue))")

There's no problem if you use generics to select a single Hashable implementation:

	import Foundation
	
	func assertHashableConsistent<T: Hashable>(a: T, b: T) {
	    assert(a == b, "a and b are equal")
	    assert(a.hashValue == b.hashValue, "a and b have the same hash value")
	}
	
	assertHashableConsistent(a: "abc" as String, b: "abc" as NSString)

The problem is that, in your case, `a` uses `NSString`'s `Hashable` in the first line, but `String`'s `Hashable` in the second line. The `assertHashableConsistent(a:b:)` function, on the other hand, ensures that `a` uses `NSString`'s `Hashable` in both lines.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-users mailing list