Search code examples
iosobjective-cswiftnsarray

Overriding an Obj-C class method from Swift which returns NSArray


I seem unable to override the following method, and have created a standalone example which has been vexing me for a few hours now.

It's almost certainly something silly, but I seem unable to override a class method in a swift class, where the base class is Objective C, and specifically the return type is an NSArray*.

I just get the error, "Method does not override any method from its superclass"

So my failure is shown below:

Error shown, with definition of class and superclass

But it works fine if the return type is changed to something simple like NSString*

Working example with NSString

Now i've tried Array<AnyObject> and played around with a couple of others, but i'm still a bit fresh with the Swift syntax so i'm almost certainly missing something obvious.


Solution

  • NSArray * is bridged to Swift as [AnyObject]! (an implicitly-unwrapped Array of AnyObject instances). Look at the generated Swift interface for [ExampleBase exampleMethod]:

    ExampleBase

    Change your method return type to [AnyObject]!.

    override class func exampleMethod() -> [AnyObject]! {
        return []
    }
    

    To specify an optional or concrete value in your Swift subclass, use an Objective-C nullability specifier:

    + (NSArray * _Nonnull)exampleMethod; bridges to override class func exampleMethod() -> [AnyObject]

    + (NSArray * _Nullable)exampleMethod; bridges to override class func exampleMethod() -> [AnyObject]?

    + (NSArray *)exampleMethod; and + (NSArray * _Null_unspecified)exampleMethod; have identical behavior and bridge to an implicitly-unwrapped optional.