User404 User404 - 7 months ago 20
Swift Question

Type 'AnyObject' does not conform to protocol 'Hashable'

I am converting my existing Objective-C Project to Swift. I am converting a function where i am getting the above error. Please check the bellow codes.

Objective-C

- (IBAction)accessoryButtonTapped:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
if (indexPath != nil) {
[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}


And here is the swift codes.

@IBAction func accessoryButtonTapped(sender: AnyObject, event: AnyObject) {
let touches: Set<AnyObject> = event.allTouches()! // I am getting the ERROR here
let touch: UITouch = touches.first!
let currentTouchPosition: CGPoint = touch.locationInView(self.tableView)
let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(currentTouchPosition)!

self.tableView(self.tableView, accessoryButtonTappedForRowWithIndexPath: indexPath)
}


Can anyone please tell me what i am doing wring ?

Answer

allTouches() function doesn't return an Set of AnyObject. It returns a Set of UITouch Object. Please check the documentation. Here is the correct code.

@IBAction func accessoryButtonTapped(sender: AnyObject, event: AnyObject) {
    let touches: Set<UITouch> = event.allTouches()!
    let touch: UITouch = touches.first!
    let currentTouchPosition: CGPoint = touch.locationInView(self.tableView)
    let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(currentTouchPosition)!

    self.tableView(self.tableView, accessoryButtonTappedForRowWithIndexPath: indexPath)
}