Drux
Drux

Reputation: 12670

Looping over Objective-C enum in Swift?

I would like to loop over an enum that was originally defined in Objective-C using Swift.

The Objective-C definition is now as follows:

typedef NS_ENUM(NSInteger, Enum) { A, B, C };

If I try for e in Enum I get this error message from the Swift compiler (in Xcode 6.1.1):

Type 'Enum.Type' does not conform to protocol Sequence.Type

What is missing? How can I let this enum behave as a sequence, if that's possible?

Upvotes: 3

Views: 1712

Answers (1)

Tommy
Tommy

Reputation: 100632

In C, and therefore in Objective-C, enums are defined to have this behaviour:

If the first enumerator has no =, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant.

So in your case you could do:

for enumerationValue in A...C

If the enum were more complicated then you'd need to do something more complicated. C doesn't ordinarily offer introspection on anything, including enumerations, so if it were more like:

typedef NS_ENUM(NSInteger, Enum) { A, B = 26, C, D = -9 };

Then you're probably approaching having to create a literal array of A, B, C and D, and enumerate through that.

Upvotes: 2

Related Questions