It will take about 3 minutes to finish reading this article.
1. General
We define an enumeration in Objective-C/C as follow:
1 | typedef enum { |
Or like this:
1 | typedef NS_ENUM(NSInteger, RoleItemType) { |
But In Swift we need to define an enumeration like this:
1 | enum CompassPoint { |
Unlike in C/OC, enumeration in Swift is a completely different thing. It is somewhat similar to struct. It is very flexible and has a wide range of uses. Enumeration in Swift has the following characteristics:
- It is of value type.
- It can conform to protocols to provide standard functionality.
- It can be extended to expand their functionality beyond their original implementation.
- It can also define initializers to provide an initial case value and define common functions and properties(computed properties).
- It supports recursion.
Enumerations in Swift are first-class types in their own right. They adopt many features traditionally supported only by classes.
2. Associated Values and Raw Values
2.1 Associated Values
Firstly, Associated Values can have different member types. for example:
1 | enum {10,0.8,"Hello"} |
Secondly, It always bases on Constant or variable. Thirdly, Associated Value will be set when you create a new constant or variable based on the enumeration member, and its value can be different each time you do so.
1 | enum Student{ |
2.2 Raw Values
Firstly, Raw Values have the same member types. for example:
1 | enum {10,35,50} |
It is pre-populated values and fixed.
1 | enum ASCIIControlCharacter: Character { |
NOTE
Raw values are not the same as associated values. Raw values are set to prepopulate values when you first define the enumeration in your code, like the three ASCII codes above. The raw value for a particular enumeration case is always the same. Associated values are set when you create a new constant or variable based on one of the enumeration’s cases, and can be different each time you do so.
Usually, An enumeration that has Declaration Type can be implicitly assigned and you do not need to write them all, for example:
1 | enum Month: Int { |
3. Add methods and properties to enumerations
1 | enum Device : Int { |
We try to extend this enumeration as follows:
1 | extension Device { |
4. Enumeration and Protocol
Enumeration can conform to protocols to provide standard functionality.
1 | enum Beverage: CaseIterable { |
5. Enumeration and Generics
A typical example of the application of enumerations in generics is ‘Optional’. ‘Optional’ is an enumeration like that:
1 | enum Optional<T> { |
Enumeration can have multiple generic parameters, for example:
1 | enum Either<T1, T2> { |
Reference
[1] https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html
[2] https://www.jianshu.com/p/6f5f7a908301
[3] https://juejin.cn/post/7053223443046596644