Functional Snippet #12: Enums Instead of Booleans

Booleans are one of the foundational types in most programming languages. In Swift and Objective-C, we use them in lots of places. However, sometimes we can introduce a new type, for code clarity. For example, consider the way you control selection behavior on UITableView:

var allowsSelection: Bool
var allowsMultipleSelection: Bool

From looking at the code, it’s not obvious what the behavior is when multiple selection is allowed, but selection is not allowed. The use of two booleans allows for four different states, although there are just three. For similar problems in our own code, we can use an enum instead of multiple booleans.

enum SelectionMode {
  case None
  case Single
  case Multiple

This encodes the three mutually exclusive selection behaviors, which allows us to replace the two Bool properties by a single property. In addition, we don’t have to set up complicated if statements with multiple branches, but we can use a single switch on the enum value.

Sometimes this technique even makes sense for a single boolean. For example, in our app we upload assets to a server, and some assets are publicly available, while others are private. Instead of a Bool, we created a new enum.

enum AccessControl {
    case Public
    case Private

Suppose we had used a boolean named isPublic, but we wanted to do something special in the case where it’s false:

if !isPublic {
  // Private asset

Whereas with our enum, we can write:

if access == .Private {

In this specific case, it is a clear win in readability.

Most recent posts