Swift For Dummies
Book image
Explore Book Buy On Amazon

When you add Swift’s features, enumerations become much more class‐like. They are no longer just collections of constants because they can now have their own properties and functions.

Here’s what a Swift enumeration can look like:

enum ParkPlace: Int {
    case park, pool, bars, track
}

With a bit of respacing, however, this can look very much like a classic C enum:

enum ParkPlace: Int {
    case park
    case pool
    case bars
    case track
}

You can assign an enumeration value to a variable in Swift using code like this:

let myPlace = ParkPlace.park

If you include this assignment and then try to print out myPlace in a playground, you’ll see the value “Enum Value” at the right.

Refer to the figure for examples of enumerations in playgrounds using variations on the code shown.

image0.jpg

You can reveal the underlying value of an enumeration using the intrinsic rawValue, as in this line of code:

println (myPlace.rawValue)

The result will be “0” because by default, enumeration raw values start at zero and the result of a println function is a string (hence the quotation marks).

You can assign your own raw values to enumeration cases. For example, you could arrange the declaration like this:

enum ParkPlace: Int {
    case park
    case pool = 25
    case bars
    case track
}

Here, .park will still be 0 by default. However, .pool is now set to 25, and the sequence continues from there. Thus, the following code snippet will print 26. If you were to set bars to 99, track would automatically become 100.

let myPlace = ParkPlace.bars
println (myPlace.rawValue)

It is common to use strings in an enumeration. Here is a sample in which the enumeration cases have strings assigned to them.

enum Place: String {
  case
    park = "park",
    pool = "swimming pool",
    bars = "climbing bars",
    track1 = "running track",
    track2 = "walking track"
}

Note in this example that there is a distinction between the case elements, which are not quoted strings and the associated values which are strings. Note also that in your code the case elements start with a period when you use them. The period is not used in the declaration.

.track would print 27.

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: