top of page

Swift: Comparing Enums With Associated Values

Comparing enums in Swift is very straightforward – as long as they don’t have associated values. In this post, we will discuss what you can do in that case.


Let’s start with a simple case:

enum TestEnum {
    case testA
    case testB
}

let testEnum1 = TestEnum.testA
let testEnum2 = TestEnum.testB
let testEnum3 = TestEnum.testA

print(testEnum1 == testEnum2) //false
print(testEnum1 == testEnum3) //true

So in this example, we are defining an enum called TestEnum, which has two cases. Then we are declaring two variables of this type and we compare them – they behave as expected and everything is working fine.


Enums With Associated Values

Now let’s look into the hard stuff. First, we add an associated value to one of the cases:


enum TestEnum {
    case testA(Int)
    case testB
}

let testEnum1 = TestEnum.testA(5)

You can use an enum with associated values to add some additional information. It can only be accessed within a switch statement though:

enum TestEnum {
    case testA(Int)
    case testB
}

let testEnum1 = TestEnum.testA(5)


switch testEnum1 {
case .testA(let a):
    print("Case testA with associated value \(a)")
case .testB:
    print("Case testB")
}

As expected, the output is

Case testA with associated value 5

Comparing Enums With Associated Values

Now let’s look into the hard stuff. First, we add an associated value to one of the cases:

enum TestEnum {
    case testA(Int)
    case testB
}

let testEnum1 = TestEnum.testA(5)
let testEnum2 = TestEnum.testB

if testEnum1 == testEnum2 {   //COMPILER ERROR!!!
    print("equal")
}

In this case, we get a compiler error:

Binary operator '==' cannot be applied to two 'TestEnum' operands

And this makes sense because it’s not clear when they are equal. For example, are two testA values equal if their associated values are equal? Or are two testA values always equal? It depends on the circumstances and the meaning of the enum.

Comments


I Sometimes Send Newsletters

Thanks for submitting!

© 2024 by Faiz Baraja.

bottom of page