[swift-users] Extend int arrays to be hashable?

Brent Royal-Gordon brent at architechies.com
Tue Sep 6 03:08:13 CDT 2016


> On Sep 6, 2016, at 12:38 AM, Jean-Denis Muys via swift-users <swift-users at swift.org> wrote:
> 
> I suppose I could make my HashableIntArray “have-a” Array<Int>, but then I would have to reimplement all the Array API with boilerplate code, which is really inelegant at best.
> 
> What did I miss?

Nothing. In the current version of Swift, the best solution is to write a wrapper HashableArray type. One thing which might help is that you don't really have to support the full interface of Array; it's enough to say:

	struct HashableArray<Element: Hashable>: Hashable {
		var elements: [Element]
		init(_ elements: [Element]) {
			self.elements = elements
		}
		
		var hashValue: Int { … }
		static func == (lhs: HashableArray, rhs: HashableArray) -> Bool { … }
	}

And then use the array operations on the `elements` property.

In the future, we hope to support conditional conformances, so you could say:

	extension Array: Hashable where Element: Hashable {
	    var hashValue: Int {
	        return self.reduce(5381) {
	            ($0 << 5) &+ $0 &+ $1.hashValue
	        }
	    }
	}

But that happy day has not yet arrived.

(When that day *does* come, I wouldn't be surprised if the Hashable conformance is in the standard library and you don't even need to implement it yourself.)

-- 
Brent Royal-Gordon
Architechies



More information about the swift-users mailing list