2

How to consume swift class from objective-c++ in ios-project?

Apple docs talk only about objective c : https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

I tried doing this -

Console.swift

public class Console : NSObject {
  public func Dump() -> Void {
      let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "Console")
      os_log("url = %@", log: log, "Some thing here")
  }
}

ConsoleDelegate.hpp

#ifndef ConsoleWrapper_h
#define ConsoleWrapper_h
#import <Foundation/Foundation.h>
#import <Interop-Swift.h>

@interface ConsoleDelegate : NSObject {
@private
  Console* console;
}

- (ConsoleDelegate*) init;
- (void) DumpWrapper;
@end
#endif /* ConsoleWrapper_h */

ConsoleDelegate.mm

#import "ConsoleDelegate.hpp"
#import <Foundation/Foundation.h>

@implementation ConsoleDelegate

- (ConsoleDelegate*) init {
  console = [[Console alloc] init];
  return self;
}

- (void) DumpWrapper {
  [console Dump];
}
@end

But i get errors like -

/path/to/file/Interop-Swift.h:192:39: No type or protocol named 'UIApplicationDelegate'

If i rename ConsoleDelegate.mm -> ConsoleDelegate.m then it compiles without any errors.

Sunil
  • 335
  • 4
  • 11
  • Try exposing the swift class to Objective C then exposing to Objective C++ from Objective C. You may also want to see https://stackoverflow.com/questions/24042774/can-i-mix-swift-with-c-like-the-objective-c-mm-files – Papershine Feb 20 '18 at 04:06
  • I tried that as well. Compiler isn't happy when i try to import objective C header file in objective C++ implementation file and complains the same error - "no type or protocol named UIApplcationDelegate" – Sunil Feb 20 '18 at 04:13
  • `UIApplicationDelegate` - are you somehow trying to use iOS code on MacOS? – Cristik Feb 20 '18 at 11:14
  • It's a iOS project and Xcode will cross compile for iOS from my MacOS. – Sunil Feb 20 '18 at 16:38

1 Answers1

0

Well, all i have to do was include the UIKit in ConsoleDelegate.hpp.

#ifndef ConsoleWrapper_h
#define ConsoleWrapper_h

#import <UIKit/UIkit.h>
#import <Foundation/Foundation.h>
#import <Interop-Swift.h>

@interface ConsoleDelegate : NSObject {
@private
  Console* console;
}

- (ConsoleDelegate*) init;
- (void) DumpWrapper;
@end
#endif /* ConsoleWrapper_h */
Sunil
  • 335
  • 4
  • 11