Swift tip: enumerations are first class types

The Book says it without any doubt:

Enumerations in Swift are first-class types in their own right

But wait, there is more! (I love the way my blog’s theme formats quotes, so I

Enumerations in Swift are first-class types in their own right. They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration’s current value, and instance methods to provide functionality related to the values the enumeration represents.

But wait, there is even more!

Enumerations can also define initializers to provide an initial member value; can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality.

Yes, if you ever had to write Objective-C for a living, sooner or later you would find yourself in a spot where you would need to loop all the values in an enumeration.

It was not a big deal, because, well, Objective-C enumerations where collections of integers. So all you had to do was end the enumeration with some sort of marker, that indicated you that you were done.

Well, Swift is different. And this time, that’s for the best. Consider an enumeration like this:

enum ApplianceForSale: Int {
    case VacuumCleaner = 0
    case WashingMachine
    case Dryer
    case DishWasher
    case CofeeMaker
    case WaterBoiler
    case Fridge
    case Toaster
    case WaffleMaker
    case RiceCooker
}

Would there be any safe and maintenable way to loop all the values in that enumeration? Indeed, there would be, thanks to Swift’s Sequences and Generators.

enum ApplianceForSale: Int {
    case VacuumCleaner = 0
    case WashingMachine
    case Dryer
    case DishWasher
    case CofeeMaker
    case WaterBoiler
    case Fridge
    case Toaster
    case WaffleMaker
    case RiceCooker
    
    static var allValues: [ApplianceForSale] {
        var index = 0
        let generator = GeneratorOf {ApplianceForSale(rawValue: index++)}
        let sequence = SequenceOf(generator)
        
        return Array(sequence)
    }
}

let allValues = ApplianceForSale.allValues
for (index, element) in enumerate(allValues) {
    println("index \(index) == element \(element)")
}

Leave a Reply

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