Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 499
Adrian_H Avatar asked May 23 '16 15:05

Adrian_H


2 Answers

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.

like image 182
JAL Avatar answered Sep 20 '22 02:09

JAL


A solution is to give the compiler more information about the type.

In ObjC declare the method

+ (NSArray<NSString *>*)exampleMethod;

then in Swift you can write

override class func exampleMethod() -> [String]
like image 45
vadian Avatar answered Sep 20 '22 02:09

vadian