官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 清涧县| 商水县| 高淳县| 三亚市| 大冶市| 通江县| 东乡县| 庄浪县| 仁化县| 石狮市| 基隆市| 乌兰浩特市| 崇礼县| 浦北县| 枝江市| 太仓市| 湄潭县| 仙桃市| 清徐县| 信宜市| 康马县| 镇宁| 肥西县| 精河县| 延寿县| 江城| 香港| 施甸县| 石家庄市| 白河县| 元谋县| 祥云县| 彩票| 清远市| 洛宁县| 娱乐| 明水县| 青海省| 庐江县| 邵武市| 邢台县|