Dive into the world of iOS development as you learn how to create, iterate, and use enumerations with this detailed tutorial.
This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.
Topics covered in this iOS Development tutorial:
Creating enumerations, Iterating through an enum using a switch statement, Enumerations with associated types
Exercise Overview
In this exercise, we’ll look at enumerations, or enums. You will learn how to create an enumerated type, assign it to a variable, then use a switch statement to determine what the current value is. Additionally, we’ll explore enumerations with associated types.
Getting Started
Launch Xcode if it isn’t already open.
Go to File > New > Playground.
Under iOS, double–click Blank.
Navigate into Desktop > Class Files > yourname-iOS App Dev 1 Class.
Save the file as: Basic Enums.playground
Click Create.
Creating Enumerations
Enumerations are another common type found in Swift. They are typically lists or groups of related variables.
In your new Playground file, delete all the code that’s there.
-
Declaring an enum should look pretty familiar by now—enums use the same syntax as classes, structs, and protocols. Create an enum called PrimaryColors as shown below.
enum PrimaryColors { }
NOTE: Because Enumerations define a new type, they are traditionally written in UpperCamelCase (just like a class or struct).
-
When writing an enum, the curly braces contain cases, or the grouped values defined in an enumeration. Add the following cases to the PrimaryColors enum:
enum PrimaryColors { case red case yellow case blue }
-
Let’s use our enum by assigning it to a new variable. Below the enum, add the following code in bold:
enum PrimaryColors { case red case yellow case blue } var color = PrimaryColors.red
We’ve created a variable called color and set it to the value red from the PrimaryColors type, using dot notation.
In the right sidebar, you should see red print.
-
Let’s see what happens when we try to print the contents of this color variable. Add the following:
var color = PrimaryColors.red print(color)
The right sidebar will show
"
red"
. Cool! -
If you want to access a different value from the same enum, you can use shorthand, as the type becomes inferred. For example, let’s set color to a different value as shown below:
print(color) color = .yellow print(color)
Notice that you didn’t need to include the PrimaryColors type again as long as you set the variable to a value within PrimaryColors.
-
Look in the right sidebar to see that the variable’s value has changed to
"
yellow"
.This is great, but it just prints the name of the case. That’s not very flexible, so let’s see how we can print a string of text when the variable equals a given case. We’ll write a print statement for each case, then use a switch statement to evaluate the enumeration.
Using a Switch Statement with an Enum
You can evaluate an enum using a switch statement. As you learned in a previous exercise, this is another form of conditional, similar to using an if statement. Switch statements are better for more complex conditions, where there are multiple potential cases. A switch statement will consider a provided value and compare it to possible matching patterns, then execute the appropriate code based on the first matching pattern it encounters.
NOTE: Even though our enumeration does not have very many cases, we do not recommend using an if statement to evaluate it. When testing more than 2 cases, the nesting makes your code harder to read and understand. We recommend using switch statements, so let’s see what they do in the context of an enum!
-
Let’s take a look. Below the print statement, add the following code as shown in bold:
print(color) switch color { case .red: print("The variable is set to RED") }
Make sure to include the space before .red and the colon after! This essentially says to consider the value of color, and in the event the value equals red, execute the print function.
-
At the end of the code, you should see a red error
. Click it to see that the switch statement must be exhaustive—that is, switch statements must include every possible value of the type being considered. We need to write a case for the remaining values in our enum.
However, we do not need to add a default clause as it’s suggesting. In an earlier exercise, we told you that unless a switch statement is evaluating an enum or boolean, you do not need a default clause.
-
Add the other two cases:
switch color { case .red: print("The variable is set to RED") case .yellow: print("The variable is set to YELLOW") case .blue: print("The variable is set to BLUE") }
Had you not put cases for all three red, yellow, and blue, the error would not have disappeared.
-
Xcode automatically removes indentation from a case statement, even if you indent it while typing. We think that makes your code harder to visually understand, so let’s indent the case and the print function associated with it. Highlight these 6 lines:
case .red: print("The variable is set to RED") case .yellow: print("The variable is set to YELLOW") case .blue: print("The variable is set to BLUE")
-
With the 6 lines selected, press Cmd–] (Right Bracket) to indent the code one level inward. Your code should now look like this:
switch color { case .red: print("The variable is set to RED") case .yellow: print("The variable is set to YELLOW") case .blue: print("The variable is set to BLUE") }
NOTE: Pressing Cmd–[ (Left Bracket) outdents the code by one level.
If it is not showing already, click the top right middle button
to show the Debug area.
-
In the bottom Debug area, you should see The variable is set to YELLOW printed.
Now that we’ve seen one way of using enum values in print statements, let’s see how else we can incorporate the contents of an enum into a print function.
Enumerations With Associated Types
It is possible to associate another type with an enumeration. This is often used when we need to express the state of an enum in a different context that requires another type (such as a string or integer).
-
At the bottom of the playground, add another enum called SecondaryColors:
enum SecondaryColors: String { }
This time, we are associating a value of type String to our enum. You will get a red error that says that an enum with no cases cannot declare a type. The fix is simple—let’s add some cases!
-
Now that we have associated a String type, we can assign values of type String to each case. Add the bold code below:
enum SecondaryColors: String { case orange = "ORANGE" case green = "GREEN" case purple = "PURPLE" }
NOTE: The values we added are called raw values (default values). When associating cases with raw values, each case in an enum must be of the same type. This is why we needed to specify that our SecondaryColors enum is of type String.
-
Assign a new variable using the SecondaryColors enum as shown below:
case purple = "PURPLE" } var colorEnum = SecondaryColors.purple
-
This is all very good, but how can we use the string value we associated to our advantage? We can access the associated value through the implicit property .rawValue. Add the following print statement shown in bold:
var colorEnum = SecondaryColors.purple print("The variable is set to \(colorEnum.rawValue)")
Here, we’re accessing the string value associated with the purple case and printing the
"
PURPLE"
value we set in our enum.In the bottom Debug area, you should see The variable is set to PURPLE printed. Notice that it’s taking the string value we set, not the enum case which is lowercase purple.
-
Let’s add a new constant using the enum type:
print("The variable is set to \(colorEnum.rawValue)") let colorString: String = SecondaryColors.orange
You’ll get an error! This is because SecondaryColors.orange is using a case, not a string value. By specifying a String type for our enum, we have given the color cases raw values, so let’s use them.
-
Add the following in bold:
let colorString: String = SecondaryColors.orange.rawValue
Xcode is happy now! The rawValue is a string type, so we can successfully associate it with the colorString constant.
-
Let’s check the value of colorString. Type the following in bold:
let colorString: String = SecondaryColors.orange.rawValue colorString
-
Check out the right sidebar to see the constant now prints:
"
ORANGE"
Enumerations are used frequently in app development, so we’ll continue to explore them in the next few exercises.
Save and close the file. Keep Xcode open, as we’ll use it in the next exercise.