[英]swift : Enum constant with type and value
我知道,枚舉常量在swift中應該是這樣的
enum CompassPoint {
case North
case South
case East
case West
}
但是我怎樣才能給第一個元素賦值,比如下面的 Objective-C 代碼
enum ShareButtonID : NSInteger
{
ShareButtonIDFB = 100,
ShareButtonIDTwitter,
ShareButtonIDGoogleplus
}ShareButtonID;
你需要給枚舉類型,然后設置值,在下面的例子中North
被設定為100
,其余的將是101
, 102
等等,就像在C
和Objective-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
。
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)"
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.