Enumerations & Associated Types

Free iOS Development Tutorial

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

  1. Launch Xcode if it isn’t already open.

  2. Go to File > New > Playground.

  3. Under iOS, double–click Blank.

  4. Navigate into Desktop > Class Files > yourname-iOS App Dev 1 Class.

  5. Save the file as: Basic Enums.playground

  6. Click Create.

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Creating Enumerations

Enumerations are another common type found in Swift. They are typically lists or groups of related variables.

  1. In your new Playground file, delete all the code that’s there.

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

  3. 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
    }
    
  4. 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.

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

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

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

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

  2. At the end of the code, you should see a red error red alert icon. 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.

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

  4. 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")
    
  5. 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.

  6. If it is not showing already, click the top right middle button show hide debug area to show the Debug area.

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

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

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

  3. Assign a new variable using the SecondaryColors enum as shown below:

       case purple = "PURPLE"
    }
    
    var colorEnum = SecondaryColors.purple
    
  4. 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.

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

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

  7. Let’s check the value of colorString. Type the following in bold:

    let colorString: String = SecondaryColors.orange.rawValue
    
    colorString
    
  8. 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.

  9. Save and close the file. Keep Xcode open, as we’ll use it in the next exercise.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn iOS & Web Development

Master iOS development, web development, coding, and more with hands-on training. iOS development involves designing apps for Apple mobile devices with tools like Xcode and SwiftUI.

Yelp Facebook LinkedIn YouTube Twitter Instagram