I have this enum:
enum GestureDirection:UInt {
case Up = 1 << 0
case Down = 1 << 1
case Left = 1 << 2
case Right
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)