False expectations: Enum

Just ran into interesting situation, when the result of concatenating a enum with a string was not the actual thing I was expecting.

I have enum with rawValue of String type, for example:

enum TestEnum: String {
case ok
case nope = "no"
}

It was used in the following way

print("tests-\(TestEnum.nope)")

And I expected to get

tests-no

as a result.

Unfortunately I got this

tests-nope

It turned out that it uses case by itself instead of its rawValue. It’s just my false expectation, but it hurts.

There are two solutions for this problem

  1. Just use actual .rawValue of the case
print("tests-\(TestEnum.nope.rawValue)")

2. Add conformance to CustomStringConvertible protocol, and leave call site as is

extension TestEnum: CustomStringConvertible {
var description: String {
return rawValue
}
}

Tadam 🎉