- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 372字
- 2021-07-02 23:54:27
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.
- 計算機組成原理與接口技術:基于MIPS架構實驗教程(第2版)
- 數據之巔:數據的本質與未來
- 數據庫程序員面試筆試真題庫
- 基于OPAC日志的高校圖書館用戶信息需求與檢索行為研究
- SQL優化最佳實踐:構建高效率Oracle數據庫的方法與技巧
- INSTANT Android Fragmentation Management How-to
- Hadoop 3實戰指南
- 深入理解InfluxDB:時序數據庫詳解與實踐
- 大數據數學基礎(R語言描述)
- Access數據庫開發從入門到精通
- R Machine Learning Essentials
- PostgreSQL高可用實戰
- Cognitive Computing with IBM Watson
- Arquillian Testing Guide
- 掌中寶:電腦綜合應用技巧