You can use Enumerations (enumeration) to define a limited collection of worth. Enumerations can make your code clearer because it allows you to substitute descriptive names for things that are abstract like integer values.
If you want to use enumerations to describe machine status, you can use the following code:
Enum State {
Case Inactive
Case Active
Case Hibernate
Case Terminated
}
var machinestate =state.inactive
In the preceding code, you define an enumeration type named state, which has four values: Inactive, Active, Hibernate, and Terminated. You can use the CASE keyword to specify the value of an enumeration, or you may use commas to separate multiple enumeration values on a single line
You can use the enumeration type as you would with other types, as shown in the example above, and you will assign state.inactive this enumeration value to the variable machinestate
You want to use the value of an enumeration type in a ternary conditional operator, if statement, in a switch statement, or anywhere else in a variable or constant can be used
Machinestate = = state.inactive? println ("Machine Inactive"):
println ("Machine State Unknown")
In the above example, machine Inactive will be printed because the value of Machinestate is state.inactive
An enumeration type can define its own value type, or you can assign other types (including integers, strings, floating-point types, and so on) to enumerated types.
To assign other types of values to an enumeration type, you must specify the type of the enumeration and then use the copy operator to assign the value. For example, if you want to define an enumeration of an alphabet and track the location of the letters, you can use the following code:
Enum alphabet:int{
Case A = 1
Case B, C, D, E, F, G, H, I
Case J, K, L, M, N, O, P, Q
Case R, S, T, U, V, W, X, Y, Z
}
In the example above, you define an enumeration type of alphabet as an integral type. This means that each alphabet value is associated with an integer. You must associate an integer value for each of the enumeration type values in the enumeration value A that's what you do. Because this is the type of shaping, Swift calculates the integer value corresponding to the remaining enumerated type value in the order you list.
You can use Alphabet as you would with state. For Alphabet, you can get the integer value corresponding to the enumeration value through the Teraw () function
For example, if you want to add the integer value of a and the integer value of B, you can use the following code:
Let result =alphabet.a.toraw () + Alphabet.b.toraw ()
Toraw () is a function that we will explain in the 27th chapter
19th Zhang Yi Lifting