Case-less enumerations

In Chapter 13, “Methods” you learned how to create a namespace for a group of related type methods. The example in that chapter looked like this:

struct Math {

static func factorial(of number: Int) -> Int { return (1...number).reduce(1, *)

}

}

let factorial = Math.factorial(of: 6) // 720

One thing you may not have realized at the time is that you could create an instance of Math, like so:

let math = Math()

The math instance doesn’t serve any purpose since it is completely empty; it doesn’t have any stored properties. In cases like this, the better design is actually to transform Math from a structure to an enumeration:

enum Math {

static func factorial(of number: Int) -> Int { return (1...number).reduce(1, *)

}

}

let factorial = Math.factorial(of: 6) // 720

Now if you try to make an instance, the compiler will give you an error:

let math = Math() // ERROR: No accessible initializers

As you learned at the beginning of this chapter, enumerations are quite powerful. They can do most everything a structure can, including having properties and methods. In order to create an instance of an enumeration though, you have to assign a member value as the state. If there are no member values, then you won’t be able to create an instance.

That works perfectly for you in this case (pun intended). There’s no reason to have an instance of Math. You should make the design decision that there will never be an instance of the type. This will prevent future developers from accidentally creating an instance and help enforce its use as you intended. So in summary, choose a case-less enumeration when it would be confusing if a valueless instance existed.

results matching ""

    No results matching ""