Inherit from a Swift class in Objective C
Unfortunately, it's not possible to subclass a Swift class in Objective-C. Straight from the docs:
You cannot subclass a Swift class in Objective-C.
See Apple's guide on interoperability for more details on what you can and cannot access with Objective-C.
As for Xcode 8.0 and earlier there is dirty-hacky solution, that probably will be fixed in the future.
If you want to subclass from swift file, you can add objc_subclassing_restricted
attribute. You can make it as macro for convenience.Code:
Swift class.
import Foundationclass 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 is not supported, and you may have any sort of bugs because of it. So it is not guide to action, and more like curious thing to know.
In fact, it can be achieved by category:
Swift code
import UIKit@objc open class TestModel: NSObject { @objc var testName: String = String()}
Objective C .h file code
#import <Foundation/Foundation.h>#import "Test-Swift.h"@interface TestModel (Add)- (void)configTestName;@end
Objective C .m file code
#import "TestModel+Add.h"@implementation TestModel (Add)- (void)configTestName { self.testName = @"12323";}@end