1

Maybe I misunderstand enums in swift, but in obj-c I was using enums like this (and using a lot):

class SomeObject;

typedef NS_ENUM(NSUInteger, SomeType) {
    Type1 = 0,
    Type2,       // = 1
    Type3,       // = 2
    TypeInvalid  // = 3
};

- (SomeType)getTypeOf(NSArray *a, SomeObject *o) {
    //for (int i = 0; i < a.count; ++i)
    //    if ([a[i] isEqual:o])
    //        return i;
    NUInteger result = [a indexOfObject:o];
    return result == NSNotFound ? TypeInvalid : result;
}

// Also I could use this:
a[Type3] = someObject;

How to do the same in Swift? Am I forced to use constants (let Type1 = 0), like in Java (public static final int Type1 = 0;)?

1
  • 2
    Rather than looping and calling isEqual:, just use indexOfObject:. Commented May 6, 2016 at 18:32

2 Answers 2

6

Simply:

enum SomeType : Int {
  case Type1, Type2, Type3, TypeInvalid
}

The Apple documentation states:

By default, Swift assigns the raw values starting at zero and incrementing by one each time

So you get Type1 with a rawValue of 0. For example:

  1> enum Suit : Int { case Heart, Spade, Diamond, Club }
  2> Suit.Heart.rawValue
$R0: Int = 0
  3> Suit.Club.rawValue
$R1: Int = 3

Note: In your example code, you'll need to replace return i with return SomeType(rawValue: i)! (although I don't quite understand the logic as apparently i is limited by a.count which might not correspond to a SomeType value)

Sign up to request clarification or add additional context in comments.

Comments

3

In addition to Ed Gamble response, you can also set enum values manually:

enum SomeType : Int {
  case Type1 = 1
  case Type2 = 2
  case Type3 = 3
  case TypeInvalid = -1
}

Using Swift enums you are not limited to Int values:

enum SomeType : String {
  case Type1 = "Type 1"
  case Type2 = "Type 2"
  case Type3 = "Type 3"
  case TypeInvalid = "Invalid type"
}

To get the inner value, you call rawValue:

let foo = SomeType.Type2
foo.rawValue // returns "Type 2"

And you can construct enums from values using init(rawValue:) method:

let rawValue = "Type 2"
let foo = SomeType(rawValue: rawValue)

Note that this init returns an optional, because it may not found a valid enum associated to that value. Having a default value makes error handling much easier:

let foo = SomeType(rawValue: rawValue) ?? SomeType.TypeInvalid

2 Comments

Thanks for the addition, but what ?? does?
?? is the nil coalescing operator. a ?? b unwraps the value of a if is not nil and returns b otherwise. It's equivalent to a != nil ? a! : b. In this case, SomeType(rawValue:) may not match and return nil and will return .TypeInvalid in that case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.