Use Enumerations in Swift
Written by Team Kodeco
An enumeration, or enum
, is a way to define a set of related values in Swift. Enums are useful when you want to represent a set of choices or options in your code. They can make your code more readable and maintainable by providing a clear and meaningful name for each value.
Here is an example of how to define an enumeration in Swift:
enum CompassPoint {
case north
case south
case east
case west
}
In this example, you defined an enumeration called CompassPoint
that contains four possible values: north
, south
, east
, and west
. These values are called cases of the enumeration.
You can use the cases of an enumeration to create instances:
var directionToHead = CompassPoint.west
directionToHead = .east
In this example, you created a variable called directionToHead
and assigned it the value .west
. You then change the directionToHead to .east
.
Using Enums in a Switch Statement
You can use a switch statement to check the value of an enumeration case:
switch directionToHead {
case .north:
print("Lots of planets have a north")
case .south:
print("Watch out for penguins")
case .east:
print("Where the sun rises")
case .west:
print("Where the skies are blue")
}
This will print “Where the sun rises”.