If you intend to use Swift Enums in a List or ForEach, it’s essential to make your enum conform to the Identifiable protocol.
Here, we will explore the process of achieving this for two types of enums those are:
- Enum without associated values
- Enum with associated values
Identifiable Protocol Overview
The Identifiable protocol provides a way to uniquely identify items. To conform, a type must return something that meets two criteria:
- It must be named ‘id’ with a generic type ‘ID’.
- The ‘ID’ type must conform to the Hashable protocol.
public protocol Identifiable<ID: Hashable> { var id: Self.ID { get } }
Simply, we need our enum to present a unique Hashable value as an id.
Enum without Associated Value
For enums without associated values, achieving conformance is straightforward since they automatically gain Hashable conformance. Here’s an example using a Direction
enum:
enum Direction: Identifiable { var id: Self { return self } case north, south, east, west }
In this case, the enum itself can be used as the ID since it already conforms to Hashable.
Enum with Associated Value
Enums with associated values don’t automatically conform to the Hashable protocol. However, by following a few extra steps, we can make them conform to the Identifiable protocol.
Conforming to Hashable
To make an enum with associated values conform to Hashable, ensure that all associated values adhere to Hashable and explicitly conform to Hashable in the enum declaration. As an example, let’s consider a Barcode
enum:
enum Barcode: Hashable { case basic(Int) case qrCode(String) }
Conforming to Identifiable
Once the enum conforms to the Hashable protocol, making it conform to Identifiable is similar to the process for enums without associated values:
enum Barcode: Hashable, Identifiable { var id: Self { return self } case basic(Int) case qrCode(String) }