Enumerations

In Swift, an enumeration defines a common type for related values and enables us to work with those values in a type-safe way. Values provided for each enumeration member can be a String, Character, Int, or any floating-point type. Enumerations can store associated values of any given type, and the value types can be different for each member of the enumeration, if needed. Enumeration members can come pre-populated with default values (called raw values), which are all of the same type. Consider the following example:

enum MLSTeam { 
case montreal
case toronto
case newYork
case columbus
case losAngeles
case seattle
}

let theTeam = MLSTeam.montreal

Enumeration values can be matched with a switch statement, which can be seen in the following example:

switch theTeam { 
case .montreal:
print("Montreal Impact")
case .toronto:
print("Toronto FC")
case .newYork:
print("NewyorkRedbulls")
case .columbus:
print("Columbus Crew")
case .losAngeles:
print("LA Galaxy")
case .seattle:
print("Seattle Sounders")
}

Enumerations in Swift are actually algebraic data types that are types created by combining other types. Consider the following example:

enum NHLTeam { case canadiens, senators, rangers, penguins, blackHawks, capitals } 

enum Team {
case hockey(NHLTeam)
case soccer(MLSTeam)
}

struct HockeyAndSoccerTeams {
var hockey: NHLTeam
var soccer: MLSTeam
}

The MLSTeam and NHLTeam enumerations each have six potential values. If we combine them, we will have two new types. A Team enumeration can be either NHLTeam or MLSTeam, so it has 12 potential values that are the sum of NHLTeam and MLSTeam potential values. Therefore, Team, an enumeration, is a sum type.

To have a HockeyAndSoccerTeams structure, we need to choose one value for NHLTeam and one for MLSTeam so that it has 36 potential values that are the product of NHLTeam and MLSTeam values. Therefore, HockeyAndSoccerTeams is a product type.

In Swift, an enumeration's option can have multiple values. If it happens to be the only option, then this enumeration becomes a product type. The following example presents an enumeration as a product type:

enum HockeyAndSoccerTeams { 
case value(hockey: NHLTeam, soccer: MLSTeam)
}

As we can create sum or product types in Swift, we can say that Swift has first-class support for algebraic data types.

Enumerations and pattern matching will be covered in detail in Chapter 4, Enumerations and Pattern Matching.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset