Swift For Dummies
Book image
Explore Book Buy On Amazon

Inside an enumeration within Swift, you can declare variables or constants. As you can see in the figure and the following listing, the enumeration contains a static variable consisting of an array with the five cases of the enumeration.

enum Place: String {
    park = "park",
    pool = "swimming pool",
    bars = "climbing bars",
    track1 = "running track",
    track2 = "walking track"
  static let facilities = [park, pool, bars, track1, 

Work through the following steps to explore the code you see here:

  1. Declare the Place enumeration.

    It has five cases.

  2. Declare a static member of the enumeration.

    Its name is facilities, and it is an array consisting of the five ­enumeration cases.

    Note that the elements of the array are the enumeration cases: They are not strings and they are not quoted.

  3. Create a variable e and set it to the raw value of the pool case of the Place enumeration.

    You are using the declaration and not an instance of the enumeration. As you see, it has the value “swimming pool” with the associated value of the case pool.

  4. If you print it, you’ll see it identified only as an Enum Value.

  5. Use fast enumeration to loop through the facilities array using amenity as the loop variable.

    You’ll see in the playground that the println statement executes five times.

  6. Create a String variable called result and set it to a blank string.

  7. In another fast enumeration loop, add each raw value (string) to result along with a comma and a blank.

  8. Print result.

    This type of code could be used to create checkboxes for all the values of the enumeration.

That use of fast enumeration would be the reverse of what is often done when you draw the interface and then declare the variables behind checkboxes or other user interface elements. In this case, you define the enumeration and its cases and then write code to create the interface elements. Try it, and you’ll be convinced that it’s faster.

About This Article

This article is from the book:

About the book author:

Jesse Feiler is a developer, consultant, and author specializing in Apple technologies. He is the creator of Minutes Machine for iPad, the meeting management app, and Saranac River Trail and is heard regularly on WAMC Public Radio for the Northeast’s The Roundtable.

This article can be found in the category: