Enumerations and the Switch Statement

An enumeration (enum for short) is a type with a discrete set of values. Define an enum describing pies:

e​n​u​m​ ​P​i​e​T​y​p​e​ ​{​
 ​ ​ ​ ​c​a​s​e​ ​A​p​p​l​e​
 ​ ​ ​ ​c​a​s​e​ ​C​h​e​r​r​y​
 ​ ​ ​ ​c​a​s​e​ ​P​e​c​a​n}l​e​t​ ​f​a​v​o​r​i​t​e​P​i​e​ ​=​ ​P​i​e​T​y​p​e​.​A​p​p​l​e

When the compiler expects the enum type, you can skip the full type name. For example:

v​a​r​ ​p​i​e​s​T​o​B​a​k​e​:​ ​[​P​i​e​T​y​p​e​]​ ​=​ ​[​]p​i​e​s​T​o​B​a​k​e​.​a​p​p​e​n​d​(​.​A​p​p​l​e​)

Swift has a powerful switch statement which, among other things, is great for matching on enum values:

l​e​t​ ​n​a​m​e​:​ ​S​t​r​i​n​gs​w​i​t​c​h​ ​f​a​v​o​r​i​t​e​P​i​e​ ​{c​a​s​e​ ​.​A​p​p​l​e​:

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide 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.