如何使用可用于 Swift 类的 std:vector 制作 Objective-c 类

Jes*_*ock 4 c++ objective-c std swift

如果我尝试在我的项目的 Swift 桥接头中包含一个使用 std:vector 的 Objective-C 类,在我的类中我会收到错误:

#import <vector>                 Error! 'vector' file not found
Run Code Online (Sandbox Code Playgroud)

有问题的桥接文件在我的自定义框架中。如果我不在桥接头中包含 Objective-c 标头,则所有编译都可以正常工作,但当然我无法从 Swift 类访问该类。

如何在我的 Swift 类中使用这个 Objective-c 类?

Stu*_*nie 5

Swift 只支持桥接到Objective-C。您需要将任何 CPP 代码/声明移动到 .mm 文件,例如:

foo.h

#import <Foundation/Foundation.h>

@interface Foo : NSObject

- (void)bar;

@end
Run Code Online (Sandbox Code Playgroud)

foo.mm

#import "Foo.h"
#import <vector>

@interface Foo() {
    std::vector<int> _array;
}

@end

@implementation Foo

- (void)bar {
    NSLog(@"in bar");
}

@end
Run Code Online (Sandbox Code Playgroud)

一种解决方案,如果您必须在其他 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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)")
Run Code Online (Sandbox Code Playgroud)