Swift枚举作为数组索引

问题描述 投票:1回答:2

也许我在swift中误解了枚举,但是在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;

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

swift enums
2个回答
6
投票

只是:

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

Apple文档说明:

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

所以你得到1型qazxsw poi的qazxsw poi。例如:

rawValue

注意:在你的示例代码中,你需要用0替换 1> enum Suit : Int { case Heart, Spade, Diamond, Club } 2> Suit.Heart.rawValue $R0: Int = 0 3> Suit.Club.rawValue $R1: Int = 3 (虽然我不太明白逻辑,因为显然return ireturn SomeType(rawValue: i)!的限制,可能与i值不对应)


3
投票

除了a.count,您还可以手动设置枚举值:

SomeType

使用Swift枚举,您不仅限于Ed Gamble response值:

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

要获得内在价值,请调用Int

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

您可以使用rawValue方法从值构造枚举:

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

请注意,此init(rawValue:)返回一个可选项,因为它可能找不到与该值关联的有效枚举。使用默认值可以更轻松地处理错误:

let rawValue = "Type 2"
let foo = SomeType(rawValue: rawValue)
© www.soinside.com 2019 - 2024. All rights reserved.