Adrian_H Adrian_H - 6 months ago 14
Swift Question

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 from 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.

JAL JAL
Answer

NSArray is bridged to Swift as [AnyObject]!. 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, 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]?

Comments