Reputation: 39091
I have this enum:
enum GestureDirection:UInt {
case Up = 1 << 0
case Down = 1 << 1
case Left = 1 << 2
case Right = 1 << 3
}
But on every case I get error:
Raw value for enum case must be a literal
I dont get it.
Swift 1.2, Xcode 6.3.2
Upvotes: 50
Views: 51741
Reputation: 540005
(Answer updated for Swift 5 and later. Solutions for older Swift versions can be found in the edit history.)
For attributes which are not mutually exclusive you can use a struct
and declare conformance to the OptionSet
protocol. The advantage is that you get all bit operations for free.
You just have to define the underlying storage type and the pre-defined values:
struct GestureDirection : OptionSet {
let rawValue : UInt8
static let top = Self(rawValue: 1 << 0)
static let down = Self(rawValue: 1 << 1)
static let left = Self(rawValue: 1 << 2)
static let right = Self(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)
Upvotes: 21
Reputation: 1745
Swift 2.2 Version : In my case I needed to Convert the String Enum Values to be used in Localisable Strings. So added this method inside my enum.
enum DisplayCellTitle: String {
case Clear
func labelTitle() -> String {
switch self {
case .Clear:
return "LBL_CLEAR".localizedWithComment("Clear")
}
}
}
And then Use it like so :
// Get the localised value of the Cell Label Title
let lblTitle = DisplayCellTitle.labelTitle(cellTitle)()
where cellTitle passed in is just one of these CellTitle Enum Values
Upvotes: 11
Reputation: 1377
You seems to want a bitwise support for your enums, but if you regards a translation of NS_OPTIONS
Objective-C in Swift, that's not represented by a Swift Enum but a struct
inherit from RawOptionSetType
.
If you need example or instructions, you can look at this NSHipster article
That's could be done with something like this :
struct UIViewAutoresizing : RawOptionSetType {
init(_ value: UInt)
var value: UInt
static var None: UIViewAutoresizing { get }
static var FlexibleLeftMargin: UIViewAutoresizing { get }
static var FlexibleWidth: UIViewAutoresizing { get }
static var FlexibleRightMargin: UIViewAutoresizing { get }
static var FlexibleTopMargin: UIViewAutoresizing { get }
static var FlexibleHeight: UIViewAutoresizing { get }
static var FlexibleBottomMargin: UIViewAutoresizing { get }
}
Regards,
Upvotes: 5
Reputation: 276506
That's because 1 << 0
isn't a literal. You can use a binary literal which is a literal and is allowed there:
enum GestureDirection:UInt {
case Up = 0b000
case Down = 0b001
case Left = 0b010
case Right = 0b100
}
Enums only support raw-value-literal
s which are either numeric-literal
(numbers) string-literal
(strings) or boolean-literal
(bool) per the language grammar.
Instead as a workaround and still give a good indication of what you're doing.
Upvotes: 40