Chapter 14. Enumerations

Up to this point, you have been using Swift’s built-in types, like integers, strings, arrays, and dictionaries. The next two chapters will show the capabilities the language provides to create your own types. The focus of this chapter is enumerations (or enums), which allow you to create instances that are one of a defined list of cases.

If you have used enumerations in other languages, much of this chapter will be familiar. But Swift’s enums also have some advanced features that make them unique.

Basic Enumerations

Create a new macOS playground called Enumerations. Define an enumeration of possible text alignments.

Example 14.1. Defining an enumeration
import Cocoa

var str = "Hello, playground"

enum TextAlignment ...

Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition 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.