简体   繁体   中英

Overriding Obj-C-methods in Swift using Swift enums

I have the following Objective-C class which uses an Objective-C enum:

MyClass.h :

typedef NS_ENUM(NSInteger, MyEnum) {
  MyEnumCase1
};

@interface MyClass : NSObject

-(void)method:(MyEnum)param;

@end

MyClass.m :

@implementation MyClass

-(void)method:(MyEnum)param {}

@end

I can subclass MyClass in Swift and override the method like this:

SubClass.swift

class SubClass: MyClass {    
  override func method(_ param: MyEnum) {}
}

But if I define the enum in Swift instead of in Objective-C, overriding the method fails:

MyClass.h :

// Forward declare the enum in Objective-C
typedef NS_ENUM(NSInteger, MyEnum);

@interface MyClass : NSObject

-(void)method:(MyEnum)param;

@end

SubClass.swift :

@objc enum MyEnum: NSInteger {
  case case1
}

class SubClass: MyClass {
  override func method(_ param: MyEnum) {} // Error
}

In this case, overriding the method fails with the error

Method does not override any method from its superclass

The enum itself works in Swift, I can add the following method to SubClass, and it compiles:

func useEnum() {
  let x = MyEnum.case1
}

Why does the overriding fail?

When I opened the Generated Interface of MyClass.h, Xcode showed something like this:

import Foundation

open class MyClass : NSObject {
}

Nothing more but comments.

Seems Swift cannot import incomplete enums , so methods which use such types are not imported neither.

So, your @objc enum MyEnum just declares a new enum type, and override func method(_ param: MyEnum) is an attempt to override a method which does not exist in its superclass, from the Swift side.

The enum itself works in Swift

Of course. The enum works even if you removed the line of typedef (with all lines using it) from MyClass.h .

The enum works even if you specify some different type than NSInteger :

@objc enum MyEnum: UInt8 {
    case case1
}

Seems you cannot write an actual definition of an enum in Swift, which is declared as an incomplete enum in Objective-C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM