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. ...

Get Swift in Depth now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.