nmokkary nmokkary - 4 months ago 9x
Swift Question

Override func error in Swift 2

This code in XCode 6 does not have error but in XCode 7 (Swift 2) this error has occurred :

Method does not override any method from its superclass

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */


When remove
word this error occurred :

Method 'touchesBegan(:withEvent:)' with Objective-C selector 'touchesBegan:withEvent:' conflicts with method 'touchesBegan(:withEvent:)' from superclass 'UIResponder' with the same Objective-C selector


You're getting your first error because much of Cocoa Touch has been audited to support Objective-C generics, meaning elements of things like arrays and sets can now be typed. As a result of this, the signature of this method has changed and since what you've written no longer matches this, you're given an error explaining that you've marked a method as override but it doesn't actually match any methods from the super class.

Then when you remove the override keyword, the error you're getting is letting you know that you've made a method that has a conflicting Objective-C selector with the real touches began method (unlike Swift, Objective-C doesn't support method overloading).

The bottom line is, in Swift 2, your touches began override should look like this.

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    // stuff

For more information on what Objective-C generics mean for your Swift code, I suggest you take a look at the Lightweight Generics section in the prerelease version of Using Swift with Cocoa and Objective-C. As of now on pages 33 & 34.