- Swift 4 Programming Cookbook
- Keith Moon
- 341字
- 2021-07-08 10:21:27
How it works...
When used in C and Objective-C, enums are defined as a type definition on top of an integer, with each case being given a defined integer value. In Swift, enums do not need to represent integers under the hood; in fact, they do not need to be backed by any type, and can exist as their own abstract concepts. Consider the following example:
enum CompassPoint {
case North, South, East, West
}
For Title, an integer-based enum doesn't seem appropriate; however, a string-based one may be. So, let's declare our enum to be string based:
enum Title: String {
case mr = "Mr"
case mrs = "Mrs"
case mister = "Master"
case miss = "Miss"
case dr = "Dr"
case prof = "Prof"
case other // Inferred as "other"
}
The enum's raw type is declared after its name and a : separator. The raw types that can be used to back the enum are limited to types that can be represented as a literal; this includes Swift base types--String, Int, Float, and Bool.
Cases can be assigned a value of the raw type; however, certain types can be inferred, and so do not need to be explicitly declared. For Int-backed enums, the inferred values are sequentially assigned starting at 0:
enum Rating: Int {
case worst // Infered as 0
case bad // Infered as 1
case average // Infered as 2
case good // Infered as 3
case best // Infered as 4
}
For string-based enums, the inferred value is the name of the case, so the other case in our Title enum is inferred to be other.
We can get the underlying value of the enum in its raw type by accessing its rawValue property:
let title1 = Title.mr
print(title1.rawValue) // "Mr"
- Mastering OpenLayers 3
- Web前端開發技術:HTML、CSS、JavaScript(第3版)
- Vue.js前端開發基礎與項目實戰
- Access 數據庫應用教程
- 數據結構簡明教程(第2版)微課版
- Implementing Cisco Networking Solutions
- Learning Concurrent Programming in Scala
- HTML5從入門到精通(第4版)
- 詳解MATLAB圖形繪制技術
- Azure Serverless Computing Cookbook
- HTML5+CSS3+jQuery Mobile APP與移動網站設計從入門到精通
- Java設計模式深入研究
- SQL Server實例教程(2008版)
- Web程序設計與架構
- VMware vRealize Orchestrator Essentials