如何使用 std:vector 使 Objective-c class 可供 Swift classes 使用

How to make Objective-c class using std:vector made available to Swift classes

如果我尝试在我的项目 Swift 桥接 header 中包括一个利用 std:vector 的 objective-C class,在我的 class我收到错误:

#import <vector>                 Error! 'vector' file not found

有问题的桥接文件在我的自定义框架中。如果我不在桥接 header 中包含 objective-c header,所有编译和工作正常,但当然我无法从 [=32 访问 class =] classes.

如何在我的 Swift class 中使用这个 objective-c class?

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 创建一个单独的 header 文件' s 桥接header,暴露你需要的:

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

将此包含在您的桥接中 header

#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)")