3

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?

Drux
  • 11,992
  • 13
  • 66
  • 116

1 Answers1

2

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.

Tommy
  • 99,986
  • 12
  • 185
  • 204
  • But apparently Swift allows looping for some enums in the way I tried (see [here](http://stackoverflow.com/questions/24007461/how-to-enumerate-an-enum-with-string-type)). So you are saying there is no (straightforward) way to achieve this with an Objective-C-based enum too, right? Also, I get `unresolved identifier A` for `for e in A ... C` and `ClosedInterval does not have a member named 'Generator'` for `for e in .A ... .C`. – Drux Jan 26 '15 at 20:31
  • That's the best I've been able to achieve based on your input so far: `for eAsInt in Enum.A.rawValue ..< Enum.C.rawValue { let e = Enum(rawValue:eAsInt) /* ... */ }` – Drux Jan 26 '15 at 21:10
  • 1
    Note that in your referenced question, they're actually defining an array `allValues` that contains an explicit list of all possible values and then iterate over `Enum.allValues` which is essentially what the last paragraph of @tommy's answer suggests. – David Berry Jan 26 '15 at 21:51