Swift:带有类型和值的枚举常量

39

我知道,在 Swift 中应该这样使用枚举常量

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

但是我该如何给第一个元素赋值,就像下面的Objective-C代码一样

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

}ShareButtonID;

只需阅读此官方文档并搜索“枚举和结构体”,希望能解决您的困惑。 - iPatel
2个回答

102

你需要给枚举类型赋值并设置对应的数值,在下面的例子中 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


6
toRaw() 已被替换为 rawValue - nacho4d
谢谢提醒,nacho4d。我已经更新了答案,并加上了一段关于更改的简短评论。 - kmikael
1
@fnc12:没有Swift 2.3版本... - kmikael

-2
struct AppConstant {
//Usage: AppConstant.IntValues.fifteen.rawValue
enum IntValues: Int {
    case zero = 0
    case one = 1
    case two = 2
    case three = 3
    case four = 4
    case five = 5
    case six = 6
    case seven = 7
    case eight = 8
    case nine = 9
    case ten = 10
    case eleven = 11
    case twelve = 12
    case thirteen = 13
    case fourteen = 14
    case fifteen = 15
    
    func asCGFloat() -> CGFloat {
        return CGFloat(self.rawValue)
    }
    
    func asFloat() -> Float {
        return Float(self.rawValue)
    }
    
    func asDouble() -> Double {
        return Double(self.rawValue)
    }
    
    func asString() -> String {
        return "\(self.rawValue)"
    }
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接