使用来自objective-c ++的swift(4.0)类

时间:2018-02-20 03:39:52

标签: swift interop objective-c++

如何在ios-project中使用objective-c ++中的swift类?

Apple docs仅谈论目标c:https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

我试过这个 -

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

但是我得到像 -

这样的错误
  

/path/to/file/Interop-Swift.h:192:39:没有命名的类型或协议   &#39; UIApplicationDelegate&#39;

如果我重命名ConsoleDelegate.mm - &gt; ConsoleDelegate.m然后编译没有任何错误。

1 个答案:

答案 0 :(得分:0)

好吧,我所要做的就是在 ConsoleDelegate.hpp 中添加UIKit

#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 */