Inherit from Swift class to Objective C

I successfully mix and match Obj-C and Swift in an Xcode 7 project. However, I cannot figure out how to inherit the Swift class in the Objective-C class (and yes, I know about declaring this Swift class as @objc for visibility). In this case, the desired superclass of the Swift class MySwiftViewController is a subclass of UIViewController . So far, in Obj-C, I inherit directly from the UIViewController and do not get access to the features that I added to MySwiftViewController .

Here is what I understand:

- Declare the Obj-C class as an inheritance from something that should be in the .h file after the ':' character:

 #import <UIKit/UIKit.h> @interface RootViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> @end 

- To make Swift classes visible, i.e. #import ed:

 #import "MyProject-Swift.h" 

However, you cannot import the automatically generated Swift bridge header into the Obj-C .h file. You also cannot redirect an opaque superclass with @class . So, is this possible and how?

+8
inheritance ios objective-c swift
source share
2 answers

Unfortunately, it is not possible to subclass the Swift class in Objective-C. Directly from the docs:

You cannot subclass the Swift class in Objective-C.

For more information on what you can and cannot get with Objective-C, see the Apple Compatibility Guide.

+20
source share

For Xcode 8.0 and earlier, there is a dirty hacker solution that is likely to be fixed in the future.

If you want to subclass from the swift file, you can add the objc_subclassing_restricted attribute. You can do this as a macro for convenience. The code:

Class Swift.

 import Foundation class SwiftClass : NSObject { func say() { print("hi"); } } 

Objc class:

 #import <Foundation/Foundation.h> #import "test-Swift.h" #define SWIFT_SUBCLASS __attribute__((objc_subclassing_restricted)) SWIFT_SUBCLASS @interface ObjcClass : SwiftClass - (instancetype)init; @end @implementation ObjcClass - (void)say { NSLog(@"oops"); } @end 

But, as I understand it, it is not supported, and you may have some errors because of this. So this is not a guide to action and looks more like a curious thing.

+3
source share

All Articles