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

后端 未结 9 1200
清酒与你
清酒与你 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:03

    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)]!
    

提交回复
热议问题