![](/img/trans.png)
[英]How to instantiate class by name in Swift without using the objective-c runtime
[英]How to make Objective-c class using std:vector made available to Swift classes
如果我嘗試在項目的Swift橋接標頭中包含使用std:vector的Objective-C類,則在我的類中出現錯誤:
#import <vector> Error! 'vector' file not found
有問題的橋接文件在我的自定義框架中。 如果我在橋接頭文件中不包含Objective-C頭文件,則所有文件都可以編譯並正常工作,但是我當然不能從Swift類訪問該類。
如何在Swift類中使用這個Objective-C類?
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
美孚+ 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)")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.