如何使用可用于 Swift 类的 std:vector 制作 Objective-c 类 [英] How to make Objective-c class using std:vector made available to Swift classes

查看:186
本文介绍了如何使用可用于 Swift 类的 std:vector 制作 Objective-c 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I attempt to include an objective-C class that utilizes std:vector in my project's Swift bridging header, in my class I get the error:

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

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

The bridging file in question is in my custom Framework. If I don't include the objective-c header in my bridging header, all compiles and works fine, but of course I can't access the class from Swift classes.

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

How can I use this objective-c class in my Swift classes?

推荐答案

Swift 仅支持桥接到 目标 C.您需要将任何 CPP 代码/声明移动到 .mm 文件中,例如:

Swift only supports bridging to Objective-C. You need to move any CPP code / declarations to the .mm file, such as:

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 的桥接头创建一个单独的头文件,并公开您需要的内容:


One solution, if you have to consume the C++ classes in other C++ / Objective-C++ code, to create a separate header file for Swift's bridging header, and expose what you need:

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

在你的桥接头中包含这个

Include this in your bridging 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

ma​​in.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)")

这篇关于如何使用可用于 Swift 类的 std:vector 制作 Objective-c 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆