Can enums with associated values have raw values?
In this article, let's look at how enums with associated values can be provided raw value as well!
To assign a raw value to an enum which doesn’t have an integer or string as a raw value, we need to make it conform to the RawRepresentable protocol.
The protocol has 2 requirements
1. init?(rawValue): A function requirement which lets us init the enum with a raw value2. rawValue: A property requirement that lets us access the raw value itself
Let’s look at the following enum
Since this enum has an associated value of n, the compiler can’t synthesize raw Int values by itself. But we can make this enum conform to RawRepresentable and bring the raw values back!
By satisfying both the requirement of the RawRepresentable protocol, we have an enum with an associated value that can be uniquely identified by its “raw” values as well!
Further reading about RawRepresentable: https://nshipster.com/rawrepresentable/