67

I'm wondering if I can somehow use an x, y pair as the key to my dictionary

let activeSquares = Dictionary <(x: Int, y: Int), SKShapeNode>()

But I get the error:

Cannot convert the expression's type '<<error type>>' to type '$T1'

and the error:

Type '(x: Int, y: Int)?' does not conform to protocol 'Hashable'

So.. how can we make it conform?

János
  • 32,867
  • 38
  • 193
  • 353
JuJoDi
  • 14,627
  • 23
  • 80
  • 126
  • +1. Do tuples as values work? – Thilo Jun 10 '14 at 01:03
  • 3
    I'm sure `(x:Int,y:Int)` is not a Hashable thing :) – Jason Coco Jun 10 '14 at 01:06
  • @Thilo yes tuples as values work – JuJoDi Jun 10 '14 at 01:07
  • 1
    @JasonCoco Why not? The hash could be `hash(x) ^ hash(y)`. – Erik Jun 10 '14 at 01:13
  • @SiLo Not that they can't be hashed, but that they don't conform to `Hashable`, which is required for the key portion of the Swift `Dictionary`. I should have surrounded in code block, sorry :) – Jason Coco Jun 10 '14 at 01:15
  • 2
    I think you should just make a struct type that is modeled this way and make it conform to `Hashable`. – Jason Coco Jun 10 '14 at 01:26
  • 1
    I don't think tuples can be made to conform since they can't be extended. – Joseph Mark Jun 10 '14 at 01:26
  • 3
    @sjeohp They can't, you would simple make a simple value type using a struct. – Jason Coco Jun 10 '14 at 01:33
  • 5
    The reason that tuples cannot be used as keys (or specifically, are not ``hashable``) is because they are not strictly immutable. If you define it using ``let``, it is immutable, but if you define it using ``var``, it is not. The hash used as a key in a dictionary MUST be immutable by the definition of a hash table, and as any kind of reasonable hash would directly depend on the values inside a container, a mutable container cannot be hashed (and likewise, an immutable container containing mutable objects cannot be reasonably hashed). – aruisdante Jun 10 '14 at 02:26
  • 2
    There are, of course, languages that let you use mutable values as keys in dictionary/map objects (such as C++), but if you mutate an object used as a key, it becomes undefined behavior. Apple doesn't dig undefined behavior, so they took the Python approach and don't allow mutable containers to be hashed. You can of course get around this using, as others have suggested, your own container that conforms to ``Hashable``, but as any reasonable hash is value-dependent, you're just asking for undefined behavior by working around the system this way, unless you make your container immutable. – aruisdante Jun 10 '14 at 02:30
  • 5
    @aruisdante The mutability of tuples is beside the point - they are value types, so, hashability aside, it would be an immutable copy of the tuple that got stored in the dictionary. The only issue is that tuples don't conform to `Hashable` and can't be extended to do so. Tuples are no more mutable than strings or `Int`s, which are just fine as Dictionary keys. – Nate Cook Sep 12 '14 at 13:59

11 Answers11

62

The definition for Dictionary is struct Dictionary<KeyType : Hashable, ValueType> : ..., i.e. the type of the key must conform to the protocol Hashable. But the language guide tells us that protocols can be adopted by classes, structs and enums, i.e. not by tuples. Therefore, tuples cannot be used as Dictionary keys.

A workaround would be defining a hashable struct type containing two Ints (or whatever you want to put in your tuple).

Lukas
  • 3,093
  • 1
  • 17
  • 9
  • 3
    Suppose I make a hashable struct unique across two Int properties. How should I map the combination of two ints to a unique hash? "x ^ y"? "x<<16 | y"? – chasew Jul 08 '14 at 16:07
  • 34
    Aww, this seems like such a total miss-out on what could have been an awesome language feature. I mean there's no reason that I can think of that they couldn't have made tuples implicitly hashable by combining the hashes of their components. It would have been a really swifty way to avoid two-dimensional dictionaries! – devios1 Mar 25 '16 at 19:22
  • 3
    Totally should be a feature, and I'd be surprised if a later version of Swift didn't add it (though v4 still doesn't have it). In Python, a tuple of hashables is automatically hashable. – sudo Oct 13 '17 at 00:10
  • 3
    This proposal has been accepted: https://github.com/apple/swift-evolution/blob/master/proposals/0283-tuples-are-equatable-comparable-hashable.md – Ashildr Jul 27 '20 at 13:02
  • @devios1 this is perhaps one reason why C++s usage of comparison is superior to hashing. Its easier to compose comparable operations for data structures like tuples. – Justin Meiners May 04 '21 at 17:40
  • 1
    There is currently an accepted evolution proposal to automatically add Hashable conformance to tuples ([SE-0283](https://github.com/apple/swift-evolution/blob/main/proposals/0283-tuples-are-equatable-comparable-hashable.md)). However, [there has been some difficulty with the implementation](https://forums.swift.org/t/implementation-issues-with-se-0283-tuples-are-ehc/46946). – Ryan Dec 05 '21 at 15:26
21

As mentioned in the answer above, it is not possible. But you can wrap tuple into generic structure with Hashable protocol as a workaround:

struct Two<T:Hashable,U:Hashable> : Hashable {
  let values : (T, U)

  var hashValue : Int {
      get {
          let (a,b) = values
          return a.hashValue &* 31 &+ b.hashValue
      }
  }
}

// comparison function for conforming to Equatable protocol
func ==<T:Hashable,U:Hashable>(lhs: Two<T,U>, rhs: Two<T,U>) -> Bool {
  return lhs.values == rhs.values
}

// usage:
let pair = Two(values:("C","D"))
var pairMap = Dictionary<Two<String,String>,String>()
pairMap[pair] = "A"
Marek Gregor
  • 3,691
  • 2
  • 26
  • 28
  • 6
    Can you explain what the `&* 31 &+` part does? – devios1 Jun 15 '16 at 03:10
  • 4
    &* and &+ are like normal operations * and + but with overflow error protection (so in case of overflow no error is thrown) – Marek Gregor Jun 15 '16 at 07:44
  • 2
    In Swift 3, `==` has been moved to a static func inside the struct: `static func ==(...) -> Bool {}` – BallpointBen Feb 23 '17 at 04:50
  • Fantastic answer. Using pairs is a great workaround for dealing with this problem in a general way. – Marchy Mar 24 '17 at 20:05
  • @BallpointBen Almost: `static func ==(lhs: Two, rhs: Two) -> Bool { ... }` – Raphael Jul 10 '17 at 12:56
  • 1
    As of swift 4.1, the hashable implementation can now be synthesized for you on a struct or enum that has values which are all hashable - just opt in by extending the Hashable protocol. See https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md. In swift 4.2 there's also the `hash(into:)` function to handle combining hashes: https://github.com/apple/swift-evolution/blob/master/proposals/0206-hashable-enhancements.md. The dev docs are also updated, see "Conforming to the Hashable Protocol". – othp Aug 08 '18 at 20:46
9

Unfortunately, as of Swift 4.2 the standard library still doesn't provide conditional conformance to Hashable for tuples and this is not considered valid code by the compiler:

extension (T1, T2): Hashable where T1: Hashable, T2: Hashable {
  // potential generic `Hashable` implementation here..
}

In addition, structs, classes and enums having tuples as their fields won't get Hashable automatically synthesized.

While other answers suggested using arrays instead of tuples, this would cause inefficiencies. A tuple is a very simple structure that can be easily optimized due to the fact that the number and types of elements is known at compile-time. An Array instance almost always preallocates more contiguous memory to accommodate for potential elements to be added. Besides, using Array type forces you to either make item types the same or to use type erasure. That is, if you don't care about inefficiency (Int, Int) could be stored in [Int], but (String, Int) would need something like [Any].

The workaround that I found relies on the fact that Hashable does synthesize automatically for fields stored separately, so this code works even without manually adding Hashable and Equatable implementations like in Marek Gregor's answer:

struct Pair<T: Hashable, U: Hashable>: Hashable {
  let first: T
  let second: U
}
Max Desiatov
  • 5,087
  • 3
  • 48
  • 56
7

No need special code or magic numbers to implement Hashable

Hashable in Swift 4.2:

struct PairKey: Hashable {

    let first: UInt
    let second: UInt

    func hash(into hasher: inout Hasher) {
        hasher.combine(self.first)
        hasher.combine(self.second)
    }

    static func ==(lhs: PairKey, rhs: PairKey) -> Bool {
        return lhs.first == rhs.first && lhs.second == rhs.second
    }
}

More info: https://nshipster.com/hashable/

norbDEV
  • 4,795
  • 2
  • 37
  • 28
5

I created this code in an app:

struct Point2D: Hashable{
    var x : CGFloat = 0.0
    var y : CGFloat = 0.0

    var hashValue: Int {
        return "(\(x),\(y))".hashValue
    }

    static func == (lhs: Point2D, rhs: Point2D) -> Bool {
        return lhs.x == rhs.x && lhs.y == rhs.y
    }
}

struct Point3D: Hashable{
    var x : CGFloat = 0.0
    var y : CGFloat = 0.0
    var z : CGFloat = 0.0

    var hashValue: Int {
        return "(\(x),\(y),\(z))".hashValue
    }

    static func == (lhs: Point3D, rhs: Point3D) -> Bool {
        return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
    }

}

var map : [Point2D : Point3D] = [:]
map.updateValue(Point3D(x: 10.0, y: 20.0,z:0), forKey: Point2D(x: 10.0, 
y: 20.0))
let p = map[Point2D(x: 10.0, y: 20.0)]!
Chris Felix
  • 59
  • 1
  • 1
5

If you don't mind a bit of inefficiency, you can easily convert your tuple to a string and then use that for the dictionary key...

var dict = Dictionary<String, SKShapeNode>() 

let tup = (3,4)
let key:String = "\(tup)"
dict[key] = ...
Peter Wagner
  • 67
  • 2
  • 1
3

You can't yet in Swift 5.3.2, But you can use an Array instead of tuple:

var dictionary: Dictionary<[Int], Any> = [:]

And usage is simple:

dictionary[[1,2]] = "hi"
dictionary[[2,2]] = "bye"

Also it supports any dimentions:

dictionary[[1,2,3,4,5,6]] = "Interstellar"
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
  • As Max already said in [this answer](https://stackoverflow.com/a/53516508/12938809), using an `[Int]` instead of `(Int, Int)` comes with a number of caveats. – Jordan Niedzielski Nov 15 '22 at 15:17
1

I suggest to implement structure and use solution similar to boost::hash_combine.

Here is what I use:

struct Point2: Hashable {

    var x:Double
    var y:Double

    public var hashValue: Int {
        var seed = UInt(0)
        hash_combine(seed: &seed, value: UInt(bitPattern: x.hashValue))
        hash_combine(seed: &seed, value: UInt(bitPattern: y.hashValue))
        return Int(bitPattern: seed)
    }

    static func ==(lhs: Point2, rhs: Point2) -> Bool {
        return lhs.x == rhs.x && lhs.y == rhs.y
    }
}

func hash_combine(seed: inout UInt, value: UInt) {
    let tmp = value &+ 0x9e3779b97f4a7c15 &+ (seed << 6) &+ (seed >> 2)
    seed ^= tmp
}

It's much faster then using string for hash value.

If you want to know more about magic number.

Volodymyr B.
  • 3,369
  • 2
  • 30
  • 48
1

Add extension file to project (View on gist.github.com):

extension Dictionary where Key == Int64, Value == SKNode {
    func int64key(_ key: (Int32, Int32)) -> Int64 {
        return (Int64(key.0) << 32) | Int64(key.1)
    }

    subscript(_ key: (Int32, Int32)) -> SKNode? {
        get {
            return self[int64key(key)]
        }
        set(newValue) {
            self[int64key(key)] = newValue
        }
    }
}

Declaration:

var dictionary: [Int64 : SKNode] = [:]

Use:

var dictionary: [Int64 : SKNode] = [:]
dictionary[(0,1)] = SKNode()
dictionary[(1,0)] = SKNode()
7foots
  • 21
  • 1
  • 3
0

Or just use Arrays instead. I was trying to do the following code:

let parsed:Dictionary<(Duration, Duration), [ValveSpan]> = Dictionary(grouping: cut) { span in (span.begin, span.end) }

Which led me to this post. After reading through these and being disappointed (because if they can synthesize Equatable and Hashable by just adopting the protocol without doing anything, they should be able to do it for tuples, no?), I suddenly realized, just use Arrays then. No clue how efficient it is, but this change works just fine:

let parsed:Dictionary<[Duration], [ValveSpan]> = Dictionary(grouping: cut) { span in [span.begin, span.end] }

My more general question becomes "so why aren't tuples first class structs like arrays are then? Python pulled it off (duck and run)."

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
-1
struct Pair<T:Hashable> : Hashable {
    let values : (T, T)
    
    init(_ a: T, _ b: T) {
        values = (a, b)
    }
    
    static func == (lhs: Pair<T>, rhs: Pair<T>) -> Bool {
        return lhs.values == rhs.values
    }
    
    func hash(into hasher: inout Hasher) {
        let (a, b) = values
        hasher.combine(a)
        hasher.combine(b)
    }
}

let myPair = Pair(3, 4)

let myPairs: Set<Pair<Int>> = set()
myPairs.update(myPair)
david_adler
  • 9,690
  • 6
  • 57
  • 97