Reputation: 3995
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?
Upvotes: 3
Views: 243
Reputation: 47886
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.
Upvotes: 2