Created
September 9, 2017 17:13
-
-
Save detomon/d87a50741f7d871d1b5da0b2d15fd94c to your computer and use it in GitHub Desktop.
Emulate Swift enum types in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/** | |
* Emulate Swift enum type. | |
*/ | |
typedef struct { | |
// define enum types | |
// (enums inside structs are not really private) | |
enum { | |
MyEnumInt, | |
MyEnumString, | |
MyEnumTuple, | |
} type; | |
// define field for each enum value | |
union { | |
int i; | |
char* s; | |
struct { | |
int x; | |
int y; | |
}; // optionally define field name, e.g., "t"; | |
}; | |
} MyEnum; | |
/** | |
* Print enum value. | |
*/ | |
static void printEnum(MyEnum const* myEnum) { | |
switch (myEnum->type) { | |
case MyEnumInt: { | |
printf("type.a: %d\n", myEnum->i); | |
break; | |
} | |
case MyEnumString: { | |
printf("type.b: %s\n", myEnum->s); | |
break; | |
} | |
case MyEnumTuple: { | |
printf("type.x: %d, type.y: %d\n", myEnum->x, myEnum->y); | |
break; | |
} | |
} | |
} | |
int main() { | |
// define enum variable | |
MyEnum myEnum; | |
// set int type together with its corresponding value | |
myEnum = (MyEnum) { | |
.type = MyEnumInt, | |
.i = 9, | |
}; | |
printEnum(&myEnum); | |
// set string type together with its corresponding value | |
myEnum = (MyEnum) { | |
.type = MyEnumString, | |
.s = "string", | |
}; | |
printEnum(&myEnum); | |
// set tuple type together with its corresponding values | |
myEnum = (MyEnum) { | |
.type = MyEnumTuple, | |
.x = 212, | |
.y = -476, | |
}; | |
printEnum(&myEnum); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment