Either I'm seeing some strange behaviour from Swift or I'm doing something wrong.
Let's say you have an obj-c class called TurtleHelper
which looks like this:
@interface TurtleHelper : NSObject
+(NSDictionary*)getTurtles;
@end
Then I want to override this method in Swift, so I do this:
class SwiftTurtles: TurtleHelper {
override class func getTurtles() -> NSDictionary {
// ...
}
}
The compiler throws the following error at me:
Overriding method with selector getTurtles has incompatible type
() -> NSDictionary
What am I doing wrong?
Classes in Swift can call and access methods, properties, and subscripts belonging to their superclass and can provide their own overriding versions of those methods, properties, and subscripts to refine or modify their behavior.
Swift Overriding Methods By using inheritance we can inherit base class properties, methods in a subclass and override base class properties or methods in subclass based on our requirements. By using override keyword in subclass we can override a base class methods with the same base class declaration.
Unfortunately, that is the case. You cannot subclass a Swift class (even if it is a subclass of NSObject and available to the Objective-C runtime) because of deliberate limitations baked into Obj-C to block subclassing Swift classes in Obj-C code.
as we know, if you need to override a method in base class in swift, you have to declare "override" keyword before that method. if that method is private, you can still "override" it in swift, just add NO override keyword.
It turns out that the answer seems to be
override class func getTurtles() -> [NSObject : AnyObject]!
From Apple's documentation:
When you bridge from an NSDictionary object to a Swift dictionary, the resulting dictionary is of type [NSObject: AnyObject]. You can bridge any NSDictionary object to a Swift dictionary because all Objective-C objects are AnyObject compatible.
Reference: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With