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

后端 未结 9 1225
清酒与你
清酒与你 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 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()
    

提交回复
热议问题