Swift-Swift中的C API枚举 [英] Swift - C API enum in Swift
问题描述
我有如下定义的C API:
I have C API defined like this:
typedef enum Foo {
A = 0,
B = 1
} Foo;
typedef struct Bar {
int a;
Foo foo;
} Bar;
如何在Swift中使用 Foo
枚举直?我知道,我可以执行 var数据:Foo = A
,但是我不喜欢这种语法,其中 A
似乎成为一些全局变量。
How can I use Foo
enum in Swift directly? I know, that I can do var data: Foo = A
, but I dont like this syntax, where A
seems to be some global variable.
我宁愿拥有 var数据:Foo = Foo.A
或类似标准枚举的东西。有办法吗?
I would rather have var data: Foo = Foo.A
or something similar like with standard enums. Is there a way?
推荐答案
C枚举作为枚举$ c $导入到Swift中c>如果它们是通过
NS_ENUM
或 CF_ENUM
宏定义的,请参见如何快速导入c枚举。
C enumerations are imported into Swift as an enum
if they are defined via the NS_ENUM
or CF_ENUM
macro, see for example How to import c enum in swift.
CF_ENUM
是在Core Foundation框架的 CFAvailability.h
中定义的,因此您必须导入如果文件尚未通过其他Core Foundation间接导入,则包含文件:
CF_ENUM
is defined in CFAvailability.h
from the Core Foundation framework, so you have to import that file if it is not yet imported indirectly via other Core Foundation include files:
#include <CoreFoundation/CFAvailability.h>
typedef CF_ENUM(int, Foo) {
A = 0,
B = 1
};
如果您查找 CF_ENUM
的定义,您会看到它是根据Clang定义的 enum_extensibility
属性,并扩展为
If you lookup the definition of CF_ENUM
then you'll see that it is defined in terms of the Clang enum_extensibility
attribute, and expands to
typedef enum __attribute__((enum_extensibility(open))) : int {
A = 0,
B = 1
} Foo;
两个声明都导入到Swift中,
Both declarations are imported to Swift as
public enum Foo : Int32 {
case A
case B
}
,后者不需要其他包含文件。
and the latter version does not need additional include files.
(用于打开和关闭之间的区别枚举,请参见 SE 0192处理未来枚举案例。)
(For the difference between "open" and "closed" enums, see SE 0192 Handling Future Enum Cases.)
这篇关于Swift-Swift中的C API枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!