13.4 Raw Values
As an alternative to associated values, enumeration values can come populated with default values (called raw values). These must all be of the same type (note the decleration of the Character
type on line 1):
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
Note the difference to associated values here: raw values are set when you define the enumeration type, whereas associated data is defined when you create an instance of an enumeration. The raw value for a particular enumeration case is always the same.
Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration.
If you are assigning String or Integer raw values, you do not need to explicitly declare each value.
When integers are the raw value, the implicit value of each case is one more than the previous case. If the first case is not set, it is given an implicit value of 0. For example, in the following planets
enumeration, each case has a raw value specifying its ordering:
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
Alternatively, if you use strings as your raw value, the case names are converted into strings and stored as the raw values. For example in the following enum:
enum CompassPoint: String {
case north, south, east, west
}
The cases have implicit values of "north"
, "south"
etc.
You can access the rawValue of a particular enumeration case using its rawValue
property:
let earthsOrder = Planet.earth.rawValue
// earthsOrder is 3
let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"
If your enumeration is defined using raw values, the enumeration automatically receives a (failable) initializer that takes a value of the raw value's type (as a parameter rawValue
) and returns either an enumeration case or nil
(i.e. an Optional enumeration case). For example:
let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet is of type Planet? and equals Planet.uranus
Of course, if you search for an invalid raw value, you will receive nil
back, and so must program accordingly:
let positionToFind = 11
if let somePlanet = Planet(rawValue: positionToFind) {
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
} else {
print("There isn't a planet at position \(positionToFind)")
}
// Prints "There isn't a planet at position 11"