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:

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

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):

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:

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 *