More about Enumerations and Associated Types

I have briefly covered Associated Types before, but I would like to discuss what I like about them a little bit further.

So, to recap, let’s assume we have an enumeration like this:

enum TrackingEvent {
    case AppStart
    case AppEnd

enum MessageType {
    case Error
    case Warning
    case Info
    case Tracking(TrackingEvent)

If we want to check what message is, we need to do this:

let message: MessageType = .Tracking(.AppEnd)

switch message {
    case .Error:
        print("error ", message)
    case .Warning:
        print("warning ", message)
    case .Info:
        print("info ", message)
    case .Tracking(let event) :
        print("I only care about this ", event)

Now, imagine we only care about the case when message matches a tracking event (any tracking event). We would need to do something like this (which as I far as I know, was the only way):

switch message {
    case .Tracking(let event):
        print("I only care about this ", event)
        print("I'll do nothing")

Notice how (as of Xcode 7.1) we need to implement something in the default block. It can not be empty.

Now, somewhere along the journey, I honestly don’t recall if it was with Swift 2 or 2.1, this was introduced:

if case .Tracking(let event) = message {
    print("trackingEvent ", event)

Syntactic sugar? Yes. Useful syntactic sugar? Hell, yes! It makes code more expressive and therefore easier to read.

And here is the playground: AssociatedTypes.playground

One Reply to “More about Enumerations and Associated Types”

Leave a Reply

Your email address will not be published. Required fields are marked *