Can enums with associated values have raw values?

Vaibhav Singh
1 min readOct 18, 2022

--

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 value

2. 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/

--

--

Vaibhav Singh
Vaibhav Singh

Written by Vaibhav Singh

iOS Engineer @ Pulselive Leading development of the Premier League App!

No responses yet