Enumerations and Raw Values

On page 39, we check to see whether the raw value obtained from an instance of an enum corresponds to an actual case of the enum.

I don’t understand why we need to do this. How would it be possible to create an instance of the the enum that isn’t an actual case of the enum? If that’s not possible, then isn’t the raw value derived from a valid instance of the enum guaranteed to be a valid input to the rawValue: initialiser?

Good question, perhaps the text should be more clear. That code snippet is intended to demonstrate how you would ‘round trip’ from an enum value to a raw value, back to the enum value. You’d typically only be doing one half of that process in a given scope, not the whole round trip as shown.

Yes, I would add a vote to making the text more clear, or a different example for enums and raw values. With the code given in the text, I tried to assign a unlisted case as below, but I got an error on that. So, then I thought I would inspect pieRawValue to see if it was an optional Int (Int?) and it was not. Thus, when the text is saying “This returns an optional…”, well that’s a bunch of flapdoodle.

[code]enum PieType: Int {
case Apple = 0
case Cherry
case Pecan

let pieRawValue = PieType.Lemon.rawValue
// gets an error

let pieRawValue = PieType.Pecan.rawValue
// pieRawValue is of type Int (not optional at all!)