Swift Enumerations
Learn how to use Swift enumerations to encapsulate a range of options within simple custom data types.
We'll cover the following
An overview of enumerations
Enumerations (typically referred to as enums) are used to create custom data types consisting of predefined sets of values. Enums are typically used for making decisions within code such as when using switch
statements. An enum might, for example, be declared as follows:
enum Temperature {
case hot
case warm
case cold
}
Note that in this example, none of the cases are assigned a value. An enum of this type is essentially used to reference one of a pre-defined set of states (in this case the current temperature being hot, warm, or cold). Once declared, the enum may, for example, be used within a switch
statement as follows:
func displayTempInfo(temp: Temperature) {
switch temp {
case .hot:
print("It is hot.")
case .warm:
print("It is warm.")
case .cold:
print("It is cold.")
}
}
It is also worth noting that because an enum has a definitive set of valid member values, the switch statement does not need to include a default case. An attempt to pass an invalid enum case through the switch
will be caught by the compiler long before it has a chance to cause a runtime error.
To test out the enum, the displayTempInfo()
function must be passed an instance of the Temperature
enum with one of the following three possible states selected:
Temperature.hot
Temperature.warm
Temperature.cold
For example:
Get hands-on with 1400+ tech skills courses.