swift:枚举常量的类型和值

时间:2014-06-07 09:23:29

标签: ios objective-c enums swift ios8

我知道,枚举常量在swift中应该是这样的

enum CompassPoint {
    case North
    case South
    case East
    case West
}

但是如何为第一个元素赋值,如下面的Objective-C代码

enum ShareButtonID : NSInteger
{
   ShareButtonIDFB = 100,
   ShareButtonIDTwitter,
   ShareButtonIDGoogleplus

}ShareButtonID;

1 个答案:

答案 0 :(得分:87)

您需要为枚举提供一个类型,然后设置值,在下面的示例中,North设置为100,其余为101102等,就像在CObjective-C中一样。

enum CompassPoint: Int {
    case North = 100, South, East, West
}

let rawNorth = CompassPoint.North.rawValue // => 100
let rawSouth = CompassPoint.South.rawValue // => 101
// etc.

更新:将toRaw()替换为rawValue