Raw and Hash values
suggest changeEnums without payloads can have raw values of any literal type:
enum Rotation: Int {
case up = 0
case left = 90
case upsideDown = 180
case right = 270
}
An enum with no raw-value type does not have a rawValue property.
enum Rotation {
case up
case right
case down
case left
}
let foo = Rotation.up
foo.rawValue //error
Integer raw values are assumed to start at 0 and increase monotonically:
enum MetasyntacticVariable: Int {
case foo // rawValue is automatically 0
case bar // rawValue is automatically 1
case baz = 7
case quux // rawValue is automatically 8
}
String raw values can be synthesized automatically:
enum MarsMoon: String {
case phobos // rawValue is automatically "phobos"
case deimos // rawValue is automatically "deimos"
}
A raw-valued enum automatically conforms to RawRepresentable. You can get an enum value’s corresponding raw value with .rawValue:
func rotate(rotation: Rotation) {
let degrees = rotation.rawValue
}
You can also create an enum from a raw value using init?(rawValue:):
let rotation = Rotation(rawValue: 0) // Rotation.up
let otherRotation = Rotation(rawValue: 45) // nil; no case has raw value 45
let str = "phobos"
if MarsMoon(rawValue: str) != nil {
print("Mars has a moon named \(str)")
} else {
print("Mars doesn't have a moon named \(str)")
}
Early Swift's hashValue for a simple enum was often the case index, starting at zero. That is not a promise of Hashable. Swift 4.2 and later use hash(into:) and do not guarantee that index.
let quux = MetasyntacticVariable(rawValue: 8)// rawValue is 8
quux?.hashValue // not guaranteed to be 3; varies between runs
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents