Swift Enums and Equatability: With and Without Associated Values

Gurjit Singh
3 min readJan 23, 2024
Photo by Stanley Dai on Unsplash

Swift enums provide a powerful way to model a set of related values. Enums can be equipped with associated values, allowing them to represent a variety of data structures.

In Swift, the Equatable protocol enables instances of a type to be compared for equality. Let's explore how enums behave with and without associated values when conforming to the Equatable protocol.

Swift Enum without Associated Values

Enums without associated values are simpler and automatically conform to the Equatable protocol, as long as they have no raw values.

Here’s an example:

enum Direction {
case north
case south
case east
case west
}

let direction1 = Direction.north
let direction2 = Direction.south
let direction3 = Direction.north

// Enum cases without associated values are not equal
if direction1 == direction2 {
print("Both directions are equal")
} else {
print("Directions are not equal")
}

// Enum cases without associated values are equal
if direction1 == direction3 {
print("Directions are equal")
} else {
print("Directions are not equal")
}

In this case, the Direction enum is equatable by default because it has no associated values. The equality comparison is based…

--

--

Gurjit Singh
Gurjit Singh

Written by Gurjit Singh

I’m Computer Science graduate and an iOS Engineer who writes about Swift and iOS development. Follow me on twitter @gurjitpt and for more articles www.gurjit.co

No responses yet