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

后端 未结 9 1219
清酒与你
清酒与你 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条回答
  •  心在旅途
    2020-12-03 05:02

    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 : 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 ==(lhs: Two, rhs: Two) -> Bool {
      return lhs.values == rhs.values
    }
    
    // usage:
    let pair = Two(values:("C","D"))
    var pairMap = Dictionary,String>()
    pairMap[pair] = "A"
    

提交回复
热议问题