Initializing with the raw value
You can use the raw value to instantiate an enumeration value with an initializer. You can use init(rawValue:) to do this, but if you try to use the value afterward, you’ll get an error:
let fifthMonth = Month(rawValue: 5)
monthsUntilWinterBreak(from: fifthMonth) // Error: value not unwrapped
There’s no guarantee that the raw value you submitted exists in the enumeration, so the initializer returns an optional. Enumeration initializers with the rawValue: parameter are failable initializers, meaning if things go wrong, the initializer will return nil.
If you’re using these raw value initializers in your own projects, remember that they return optionals. If you’re unsure if the raw value is correct, you’ll need to either check for nil or use optional binding. In this case, the value 5 must be correct so it’s appropriate to force unwrap the optional:
let fifthMonth = Month(rawValue: 5)! monthsUntilWinterBreak(from: fifthMonth) // 7
That’s better! Now there’s no error, and monthsUntilWinterBreak(from:) returns 7 as expected.