问题
I have C API defined like this:
typedef enum Foo {
A = 0,
B = 1
} Foo;
typedef struct Bar {
int a;
Foo foo;
} Bar;
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.
I would rather have var data: Foo = Foo.A
or something similar like with standard enums. Is there a way?
回答1:
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
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
};
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;
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.
(For the difference between “open” and “closed” enums, see SE 0192 Handling Future Enum Cases.)
来源:https://stackoverflow.com/questions/60559599/swift-c-api-enum-in-swift