Enumerations and associated types

This one is a neat little thing, but I think it totally deserves a post.

Swift enumerations support Associated Types, which are basically values of any given type, that can be stored in a specific enumeration case.

Here is an example:

enum TrackingEvent {
    case AppStart
    case AppEnd

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

let message: MessageType = .Tracking(.AppEnd)

The use case? In this case, providing two levels of hierarchical abstraction, with just one type.

The more I use Swift, and the more I’m letting go of the old patterns, the more I enjoy it.


One Reply to “Enumerations and associated types”

Leave a Reply

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