Raw value for enum case must be a literal

后端 未结 4 1134
花落未央
花落未央 2021-02-06 22:38

I have this enum:

enum GestureDirection:UInt {
    case Up =       1 << 0
    case Down =     1 << 1
    case Left =     1 << 2
    case Right          


        
4条回答
  •  误落风尘
    2021-02-06 23:18

    For attributes which are not mutually exclusive I would also recommend to use a struct based on RawOptionSetType as @Vincent suggested. One advantage is that you get all bit operations for free.

    Here is a full working example:

    struct GestureDirection : RawOptionSetType {
        let rawValue : UInt8
        init(rawValue: UInt8) {
            self.rawValue = rawValue
        }
    
        init(nilLiteral: ()) {
            self.rawValue = 0
        }
        static var allZeros: GestureDirection { return self(rawValue: 0) }
    
        static var Top:   GestureDirection { return self(rawValue: 1 << 0) }
        static var Down:  GestureDirection { return self(rawValue: 1 << 1) }
        static var Left:  GestureDirection { return self(rawValue: 1 << 2) }
        static var Right: GestureDirection { return self(rawValue: 1 << 3) }
    }
    

    Usage:

    // Initialize:
    var direction : GestureDirection = .Top | .Right
    
    // Test:
    if (direction & .Top) != nil {
       // ...
    }
    
    // Add an option:
    direction |= .Left
    
    // Remove an option:
    direction &= ~(.Right)
    

    Update for Swift 2: As of Swift 2, this can be simpler done with the new OptionSetType protocol, which offers a set-like interface (see also the recently added answers to How to create NS_OPTIONS-style bitmask enumerations in Swift?).

    We just have to define the underlying storage type and the pre-defined values:

    struct GestureDirection : OptionSetType {
        let rawValue : UInt8
    
        static let Top   = GestureDirection(rawValue: 1 << 0)
        static let Down  = GestureDirection(rawValue: 1 << 1)
        static let Left  = GestureDirection(rawValue: 1 << 2)
        static let Right = GestureDirection(rawValue: 1 << 3)
    }
    

    Usage:

    // Initialize:
    var direction : GestureDirection = [ .Top, .Right ]
    
    // Test:
    if direction.contains(.Top) {
        // ...
    }
    
    // Add an option:
    direction.insert(.Left)
    
    // Remove an option:
    direction.remove(.Right)
    

提交回复
热议问题