You use an enumeration (or an enum) to define a restricted set of values.
Enums make your code clearer because you can use descriptive names
instead of something abstract like an integer value.
If you wanted to define an enumeration to describe a machine state, you
could do something like Listing 19-1.
Listing 19-1. Defining Enumerations
enum State {
case Inactive
case Active
case Hibernate
case Terminated
}
var machineState = State.Inactive
In Listing 19-1, you defined an enum named State that can have four values:
Inactive, Active, Hibernate, and Terminated. You specify enum values with
the case keyword. You can specify one value per case keyword, or you can
provide a comma-separated list of enum values on one line.
You can use enumeration types like other types. In Listing 19-1, you are
assigning the value State.Inactive to the variable machineState.
You can also reference the enum type in the ternary conditional operator
(Chapter 16), if statements (Chapter 23), switch statements (Chapter 24),
and anywhere else variables or constants are used.
Listing 19-2 shows an example of how you would use the State enum with
the ternary conditional operator.
You use an enumeration (or an enum) to define a restricted set of values.
Enums make your code clearer because you can use descriptive names
instead of something abstract like an integer value.
If you wanted to define an enumeration to describe a machine state, you
could do something like Listing 19-1.
Listing 19-1. Defining Enumerations
enum State {
case Inactive
case Active
case Hibernate
case Terminated
}
var machineState = State.Inactive
In Listing 19-1, you defined an enum named State that can have four values:
Inactive, Active, Hibernate, and Terminated. You specify enum values with
the case keyword. You can specify one value per case keyword, or you can
provide a comma-separated list of enum values on one line.
You can use enumeration types like other types. In Listing 19-1, you are
assigning the value State.Inactive to the variable machineState.
You can also reference the enum type in the ternary conditional operator
(Chapter 16), if statements (Chapter 23), switch statements (Chapter 24),
and anywhere else variables or constants are used.
Listing 19-2 shows an example of how you would use the State enum with
the ternary conditional operator.
การแปล กรุณารอสักครู่..
