In Swift can I use a tuple as the key in a dictionary?

后端 未结 9 1166
清酒与你
清酒与你 2020-12-03 04:15

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>()


        
相关标签:
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
    }
    
    0 讨论(0)
  • 2020-12-03 04:44

    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/

    0 讨论(0)
  • 2020-12-03 04:45

    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.

    0 讨论(0)
  • 2020-12-03 04:52

    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] = ...
    
    0 讨论(0)
  • 2020-12-03 04:54

    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()
    
    0 讨论(0)
  • 2020-12-03 04:56

    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).

    0 讨论(0)
提交回复
热议问题