簡體   English   中英

swift:具有類型和值的枚舉常量

[英]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 ,其余的將是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

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM