Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding an Obj-c class function in Swift

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?

like image 653
henryeverett Avatar asked Sep 25 '14 11:09

henryeverett


People also ask

Can we override class method in Swift?

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.

How do you override a function in Swift?

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.

Can Objective C class inherit from Swift class?

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.

Can we override private method in Swift?

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.


1 Answers

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

like image 64
henryeverett Avatar answered Oct 27 '22 20:10

henryeverett