O'Reilly logo

Cocoa Programming for OS X: The Big Nerd Ranch Guide by Aaron Hillegass, Adam Preble, Nate Chandler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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​:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required