Swift 仅支持桥接到 Objective-C。您需要将任何 CPP 代码/声明移动到 .mm 文件中,例如:
Foo.h
#import <Foundation/Foundation.h>
@interface Foo : NSObject
- (void)bar;
@end
Foo.mm
#import "Foo.h"
#import <vector>
@interface Foo() {
std::vector<int> _array;
}
@end
@implementation Foo
- (void)bar {
NSLog(@"in bar");
}
@end
一种解决方案,如果您必须在其他 C++/Objective-C++ 代码中使用 C++ 类,则为 Swift 的桥接头创建单独的头文件,并公开您需要的内容:
Foo.h
#import <Foundation/Foundation.h>
#import <vector>
@interface Foo : NSObject {
std::vector<int>* _bar;
}
@property (atomic, readonly) std::vector<int>* bar;
@property (readonly) size_t size;
- (void)pushInt:(int)val;
- (int)popInt;
@end
Foo+Swift.h
将其包含在您的桥接头中
#import <Foundation/Foundation.h>
#import <stdint.h>
@interface Foo : NSObject
@property (readonly) size_t size;
- (void)pushInt:(int)val;
- (int)popInt;
@end
Foo.mm
#import "Foo.h"
@implementation Foo
@synthesize bar;
- (instancetype)init {
if (self = [super init]) {
_bar = new std::vector<int>();
}
return self;
}
- (void)dealloc {
delete _bar;
}
- (void)pushInt:(int)val {
_bar->push_back(val);
}
- (int)popInt {
if (_bar->size() == 0) {
return -1;
}
auto front = _bar->back();
_bar->pop_back();
return front;
}
- (size_t)size {
return _bar->size();
}
@end
main.swift
#import Foundation
let f = Foo()
f.pushInt(5);
f.pushInt(10);
print("size = \(f.size)")
print("\(f.popInt())")
print("\(f.popInt())")
print("size = \(f.size)")