Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude an C enum case when using the type in Swift

Tags:

c

enums

swift

In my C code I generally have an enum case called count at the end. But when I use my enum in Swift it will also have that value, which I must handle in switch statements.

Is there some attribute I can use to exclude a case when importing into Swift?

like image 703
Michael Ozeryansky Avatar asked Jan 25 '19 02:01

Michael Ozeryansky


1 Answers

You can use the NS_SWIFT_UNAVAILABLE macro on enumerators:

typedef NS_ENUM(unsigned, Foo) {
    bar,
    baz,
    count NS_SWIFT_UNAVAILABLE("Count does not represent a case")
};

NS_SWIFT_UNAVAILABLE, like any __attribute__ that you want to apply to an enumerator, goes after the enumerator name but before the = if you need one.

The macro is defined if you include <Foundation/Foundation.h>. If you include CoreFoundation, you get CF_SWIFT_UNAVAILABLE, which does the same thing. If you include neither, you can use the long form:

__attribute__((availability(swift, unavailable, message="your message")))

Enumerators that are annotated with NS_SWIFT_UNAVAILABLE won't show up in autocomplete, and won't cause build issues if they're not handled on the Swift side. If you attempt to use it, you get a hard error that includes your message.

Keep in mind that starting with Swift 5, you may need to use NS_CLOSED_ENUM instead of NS_ENUM if your purpose is to avoid having a default case.

like image 141
zneak Avatar answered Nov 09 '22 11:11

zneak