简体   繁体   中英

swift : Enum constant with type and value

I know, enumeration constant should be like this in swift

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

But how can I assign value to first element, like Objective-C code as below

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

}ShareButtonID;

You need to give the enum a type and then set values, in the example below North is set as 100 , the rest will be 101 , 102 etc, just like in C and Objective-C .

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

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

Update : Replace toRaw() with 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)"
    }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM