Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance from an Objective-c base view controller from Swift

I am trying to migrate a UIViewController Objective-C class to Swift. This view controller is inheriting from a BaseViewController where I have common functionality that I want to have in all controllers. The problem I am having is that the generated myproject-Swift.h is not able to find my BaseViewController.

Is there any way to implement a UIViewController in swift that inherits from a BaseViewController (subclass of UIViewController) written in Objective-C? Is there a bridging problem?

It can be reproduced with this minimal code:

BaseViewController.h

#import <UIKit/UIKit.h>

@interface BaseViewController : UIViewController 
@end

BaseViewController.m

import "BaseViewController.h"

@implementation BaseViewController
@end

ViewController.swift

import UIKit

class ViewController : BaseViewController {

}

AppDelegate.m

#import "AppDelegate.h"
#import "projectname-Swift.h"   // Replace with your project name

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ViewController *vc = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];

    return YES;
}

projectname-Bridging-Header.h

#import "BaseViewController.h"
like image 325
atxe Avatar asked Dec 11 '25 19:12

atxe


1 Answers

As pointed out in the accepted answer on How can I add forward class references used in the -Swift.h header?

Interoperability guide (Importing Swift into Objective-C):

If you use your own Objective-C types in your Swift code, make sure to import the Objective-C headers for those types prior to importing the Swift generated header into the Objective-C .m file you want to access the Swift code from.

The example is solved by importing BaseViewController before the importing projectname-Swift.h in:

AppDelegate.m

#import "AppDelegate.h"
#import "BaseViewController.h"
#import "projectname-Swift.h"   // Replace with your project name
// ...
like image 105
atxe Avatar answered Dec 14 '25 13:12

atxe