Search code examples
swiftnsdictionary

Swift: Dictionary Key as CGRect


I need to save the frame of a button as a key and the index from an array as its value. Below is the code:

var buttonLocationWithIndex = Dictionary<CGRect, Int>()

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    for (index, point) in enumerate(self.points){
        let pointButton = UIButton()
        pointButton.frame = point.bounds
        self.buttonLocationWithIndex[point.frame] = index
        self.view.addSubview(pointButton)
    }

I'm getting an error when trying to declare the dictionary: Type 'CGRect' does not confirm to protocol 'Hashable'

UPDATE

func pressed(sender: UIButton!) {
    var alertView = UIAlertView();

    alertView.addButtonWithTitle("Ok");
    alertView.title = "title";
    var boundsIndex = self.buttonLocationWithIndex[sender.frame]
    var value = self.points(boundsIndex)
    alertView.message = value
    alertView.show();
}

Error: Cannot invoke points with an arguments list of type (Int?)'


Solution

  • Implement Hashable protocol on CGRect trough an extension.

    extension CGRect: Hashable {
        public func hash(into hasher: inout Hasher) {
            hasher.combine(origin.x)
            hasher.combine(origin.y)
            hasher.combine(size.width)
            hasher.combine(size.height)
        }
    }
    

    It will allow you to use CGRect as a key.