Skip to content

Enumerations

Vihan edited this page Dec 1, 2018 · 3 revisions

Enumerations represent a finite group of possible parameters. Enumerations are useful when depending on the value you will conditionally execute some code. Additionally, 'associated enumerations' allow you to have different types for a single value.

Enumerations

Typical enumerations are declared as:

enum Planets {
    case mercury
    case venus
    case earth
    case mars
    case jupiter
    case saturn
    case uranus
    case neptune
}

now if I have a function that, lets say returns the amount of types a planet has been visited. That could take the enumeration as a parameter:

func howManyVisitsFor(planet: Planets) -> Int { ... }

now howManyVisitsFor(planet:) can be called using howManyVisitsFor(planet: Planet.earth)

Enumeration Comparisons

One way to check what the value of an enumeration statement is, is to use an if statement with the == or != operator:

if planet == Planet.earth { print("Home sweet home!") }
if planet != Planet.earth { print("Probably not habitable :(") }

another way is to use a switch statement:

switch planet {
    case .earth: // ...
}

For more information reference the section on switch statements.