0

I have a swift project and my initial UIViewController is a swift class.

From the initial ViewController, I added a new Viewcontroller in my storyboard and set an objective-c class (FirstViewController.h) for it.

In my project, I have another swift class (DataManager.Swift) which is a subclass of NSObject.

Now I want to create an instance of this DataManager.swift in my objective-C class (FirstViewController.m). But unfortunately, i couldn't create this instance, giving me an error like - Receiver 'DataManager' for class message is a forward declaration

What can I do now to resolve this issue? Is it possible to access swift class from Objectibe-C class while project is in swift?

My FirstViewController.m,

#import "FirstViewController.h"
@class DataManager;

@interface FirstViewController ()

@property (nonatomic, strong) DataManager *dataManager;

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   _dataManager = [[DataManager alloc] init]; //This line giving me that error
}
@end

My DataManager.swift class,

import UIKit;

@objc class DataManager: NSObject {
    var a: Int = 0
}

My BridgingHeaderFile,

#ifndef BridgingHeader_h
#define BridgingHeader_h
#import "FirstViewController.h"
#endif
Kathiresan Murugan
  • 2,783
  • 3
  • 23
  • 44
Nuibb
  • 1,800
  • 2
  • 22
  • 36

1 Answers1

4

You should import your swift module into your .m file with this syntax:
#import "ModuleName-Swift.h" where ModuleName usually is your Project Name.
NOTE: adding -Swift suffix is important!

Also @class DataManager; will be redundant after import.

arturdev
  • 10,884
  • 2
  • 39
  • 67
  • 1
    This will be only half a success - judging by OPs Swift code sample, he will also need to make the class `public` and mark all its properties/methods as `@objc public` for them to be visible in Obj-C. This of course depends on Swift version that OP is using - these markers are required for Swift 4.2 – Losiowaty Mar 21 '19 at 08:41
  • What will happen if the module name has space like "My Project"? Importing "My Project-Swift.h" isn't working here. How should I import this in this case? – Nuibb Mar 21 '19 at 09:00
  • @Nuibb yes, spaces should be replaced with "_" – arturdev Mar 21 '19 at 10:10