Xvolks Xvolks - 7 months ago 25
Swift Question

Is there a way to define a swift enum with power of 2 (or calculated value)

Is there a way to do something like this in Swift 2 ?

enum Placement: Int, OptionSetType {
case
Left = 1 << 0,
Right = 1 << 1,
Center = 1 << 2,
Top = 1 << 3,
Bottom = 1 << 4,
Middle = 1 << 5
;
....
}


The actual problem is that the compiler is not smart enough to see that those values are constants but more readable than the result.

So, is there some syntax sugar that permit such declaration ?

Answer

As @Martin R said, you need struct.

struct Placement: OptionSetType {
    let rawValue: Int

    init(rawValue: Int) {
        self.rawValue = rawValue
    }

    static var Left = Placement(rawValue: 1 << 0)
    static var Right = Placement(rawValue: 1 << 1)
    static var Center = Placement(rawValue: 1 << 2)
    static var Top = Placement(rawValue: 1 << 3)
}
Comments