Question re Initializing with an Enum Type

My course states the following regarding enums:

The initialization of an enum type is straightforward: a specific member of the enum is assigned to a variable or constant. Alternatively, enums can also be initialized with raw values. Here we initialize a constant of type, AmericanLeagueWest , using a raw value:

let myFavoriteTeam = AmericanLeagueWest(rawValue: "Oakland")

To test out the latter initialization method, I wrote the following:

enum ShoeStyleTypeTwo: Int {
    case mules
    case spectators
    case mocassins
    case flats
}

var myMuleCollection = ShoeStyleTypeTwo(rawValue: 6)
print(myMuleCollection.rawValue)

However, upon compiling, I get the following error:

Value of optional type 'ShoeStyleTypeTwo?' must be unwrapped to refer to member 'rawValue' of wrapped base type 'ShoeStyleTypeTwo'

Could someone please tell me why this is generating an error? My lessons say nothing about encountering this error for some reason. Perhaps something is wrong with my code?

Your enum has 4 cases, with raw values 0, 1, 2, and 3.

However its raw-value initializer takes an Int parameter, which could have a value outside that set.

Therefore, raw-value initializers are “failable”, meaning they actually produce an Optional value of the enum, so that if the provided raw value does not match one of the cases, the initializer produces nil.

You can unwrap optionals in a variety of ways. Your course probably has a section on the topic, or you can read about it in The Swift Programming Language.

Generally you want to use if let or guard let to unwrap optionals, but you can also use optional chaining (?.), nil coalescing (??), force unwrapping (!), and even functional constructs like map.

5 Likes