Chapter 2. Modeling data with enums

 

This chapter covers

  • How enums are an alternative to subclassing
  • Using enums for polymorphism
  • Learning how enums are “or” types
  • Modeling data with enums instead of structs
  • How enums and structs are algebraic types
  • Converting structs to enums
  • Safely handling enums with raw values
  • Converting strings to enums to create robust code

Enumerations, or enums for short, are a core tool used by Swift developers. Enums allow you to define a type by enumerating over its values, such as whether an HTTP method is a get, put, post, or delete action, or denoting if an IP-address is either in IPv4 or IPv6 format.

Many languages have an implementation of enums, with a different type of implementation per language. Enums in Swift, unlike in C and Objective-C, aren’t only representations of integer values. Instead, Swift borrows many concepts from the functional programming world, which bring plenty of benefits that you’ll explore in this chapter.

In fact, I would argue that enums are a little underused in Swift-land. I hope to change that and help you see how enums can be surprisingly useful in many ways. My goal is to expand your enum-vocabulary so that you can directly use these techniques in your projects.

First, you’ll see multiple ways to model your data with enums and how they fare against structs and classes.

2.1. Or vs. and

2.2. Enums for polymorphism

2.3. Enums instead of subclassing

2.4. Algebraic data types

2.5. A safer use of strings

2.6. Closing thoughts

Summary

Answers