Swift枚举作为数组索引

Bor*_*rzh 1 enums swift

也许我在swift中误解了enum,但是在obj-c中我使用了这样的枚举(并且使用了很多):

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;
Run Code Online (Sandbox Code Playgroud)

如何在Swift中做同样的事情?我是否被迫使用常量(let Type1 = 0),就像在Java(public static final int Type1 = 0;)中一样?

GoZ*_*ner 6

只是:

enum SomeType : Int {
  case Type1, Type2, Type3, TypeInvalid
}
Run Code Online (Sandbox Code Playgroud)

Apple文档说明:

默认情况下,Swift会从零开始分配原始值,每次递增1

所以,你用得到的Type1 rawValue0.例如:

  1> enum Suit : Int { case Heart, Spade, Diamond, Club }
  2> Suit.Heart.rawValue
$R0: Int = 0
  3> Suit.Club.rawValue
$R1: Int = 3
Run Code Online (Sandbox Code Playgroud)

注意:在你的示例代码中,你需要替换return ireturn SomeType(rawValue: i)!(虽然我不太明白逻辑,因为它显然i受限于a.count哪个可能与SomeType值不对应)