Explain the use of the enum enumeration type in Swift
- 2020-05-19 06:00:02
- OfStack
1. The introduction
In the Objective-C language, where there is no actual integer data, enums in Swift are more flexible. Instead of assigning value types to them, developers can use enums as independent types, or assign values to them, whether they are characters, strings, integers, or floating point data.
2. Enumeration syntax
The enum keyword in Swift is used to create enumeration, and case is used to create each enumeration value, as shown below:
// Create an enumeration of last names , and Objective-C Different, Swift Enumeration does not assign values by default
enum Surname {
case zhang
case The king
case li
case zhao
}
// create 1 Variables of type enumeration
var myName = Surname. zhang
// If you can automatically infer the type Enumeration types can be omitted
myName = . li
var myName2:Surname = . The king
You can also write all the enumeration values in the same case, separated by commas:
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
Enumeration is often used in conjunction with Switch statements. Here is an example:
switch myName {
case . zhang :
print(" zhang ")
case . The king :
print(" The king of surnames ")
case . li :
print(" Surname li ")
case . zhao :
print(" Surname zhao ")
}
3. Related values of enumeration
An interesting feature of enums in Swift is that they can be set to a number of related values through which developers can obtain additional passed values from common enumeration values. An example is as follows:
enum Number {
case one(count:Int)
case two(count:Int)
case three(count:Int)
case four(count:Int)
}
var num = Number.one(count: 5)
switch num {
// To obtain num The relative value
case Number.one(let count):
print(count)
default:
print(num)
}
// if 1 Are constants in all relationships, let Keywords can also be extracted outside of parentheses
switch num {
// To obtain num The relative value
case let Number.one(count):
print(count)
default:
print(num)
}
With the syntax of correlation value, the flexibility of enumeration is greatly increased. For example, for a shape enumeration, the possible enumeration values are rectangle, circle, etc. The enumeration value of rectangle can provide the correlation value of width and height, and the enumeration value of circle can provide the correlation value of radius, which makes the development more flexible.
4. The original value of the enumeration
The original value can also be understood as setting a concrete type for the enumeration, as shown below:
enum Char:String {
case a = "A"
case b = "B"
case c = "C"
}
// " A "
var char = Char.a.rawValue
Note that if the enumeration is of type Int, it is similar to Objective-C, and the original value of the enumeration increases from the first:
enum Char:Int{
case a = 0
case b
case c
}
//1
var char = Char.b.rawValue
It is also possible to create enumeration objects by means of original values, as shown below:
enum Char:Int{
case a = 0
case b
case c
}
//1
var char = Char.b.rawValue
//b
var char2 = Char(rawValue:1)
When enumeration objects are created with the original value, it is possible that the creation fails, for example, if the original value passed in does not exist, the Optional value nil is returned.
4. Recursive enumeration
Recursive enumeration is one of the difficult parts of the Swift enumeration. In fact, it is not 10 points difficult to understand. As long as developers understand the essence of enumeration, recursive enumeration is easy to understand. First of all, recursion is an algorithm, which can be simply understood as calling itself, while enumeration is not actually a function, which does not perform an operation, but only expresses a data or it can also express an expression, as shown below:
enum Expression {
// Said to add
case add
// Said to reduce
case mul
}
The concept of correlation values was mentioned earlier, so for the example above, you can add two correlation values as parameters for the add and mul enumeration values.
enum Expression {
// Said to add
case add(Int,Int)
// Said to reduce
case mul(Int,Int)
}
In this way, the following formula can actually represent a 5+5 expression:
var exp = Expression.add(5, 5)
Again, I want to emphasize one point. This exp only expresses the expression of 5+5, which is a convention. It does not really operate 5+5. Now the question is, how do you express a compound expression like (5+5)*5 using the enumeration above? You can use recursive enumeration to create (5+5) again as a value related to the enumeration value, as follows:
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
0
Above, exp4 actually expresses the (5+5)*5 process. Note that the recursive enumeration value must be declared with the indirect keyword. The best way to handle recursive enumerations is through recursive functions, as shown in the following example:
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
1
If all case in an enumeration are recursive, the entire enumeration can be declared as recursive:
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
2
5. 1 summary of some key points and difficulties
Enumeration syntax, enum begins, each line member's definition begins with the case keyword, and 1 line can define multiple keywords
enum CompassPoint {
case North
case South
case East
case West
}
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
On case North, South East, the value is not equal to 0,1,2,3 West, but their itself is its own value, and the type of the value is to CompassPoint
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
4
Separate enumeration values with switch to perform different operations. case within switch must contain all branches of the enumeration, otherwise the compilation will fail. Of course, you can use default when it is inconvenient to enumerate all the enumerated values
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
5
The elements of an enumeration can be combined values (associated value), as illustrated by an example of an enumeration of a barcode that can store a 1-dimensional barcode (composed of three integers) and a 2-dimensional barcode (composed of strings)
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
6
Within case, if the types are let or var, the keyword can be advanced between case and enumerated types, as follows:
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
7
The enumeration of the original value type is followed by the enumeration name by the data type, and its enumeration members have been assigned initial values at the time of definition and cannot be changed. Compared with the enumeration of the combined value type, the combined value only sets the value of that enumeration when the enumeration value is assigned to a variable.
The primitive value enumeration is more like the C language's enumeration, such as the integer primitive value enumeration, whose member values are incremented if not specified.
The primitive value enumeration is also like a dictionary type, and is bidirectional in that it can obtain both the original value of the member through the enumeration member and the enumeration member through the original value. It can also be seen that the original value of this enumeration cannot appear the same value
// The type of the original value enumeration follows the enumeration name, and the data type of the original value of its members is the specified type
enum ASCIIControlCharacter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}
//Int The original value of the enumeration member is incremented, for example Venus The value is 2 . Earth The value is 3
enum Planet: Int {
case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
// Can be achieved by toRaw Method to get the original value of the enumeration member
let earthsOrder = Planet.Earth.toRaw()
// earthsOrder The value is 3 , the data type is Int
// Can be achieved by fromRaw Method to get the enumeration member corresponding to the original value
let possiblePlanet = Planet.fromRaw(7)
// possiblePlanet Data type Planet? The value is Planet.Uranus
// because fromRaw The original value of may not have a corresponding enumeration member, so the type returned is 1 Three optional variable values
let positionToFind = 9
if let somePlanet = Planet.fromRaw(positionToFind) {
switch somePlanet {
case .Earth:
println("Mostly harmless")
default:
println("Not a safe place for humans")
}
} else {
println("There isn't a planet at position \(positionToFind)")
}
// There is no original value of 9 Member, so print "There isn't a planet at position 9"