How to create enumerations in Swift

Overview

The enumeration in Swift is also known as enum. Enums are user-defined data types with a fixed set of related values.

Syntax

enum NameOfEnum{
case value
}
Syntax for creating Enumeration in Swift

Parameters

  • NameOfEnum: This is the name we want to give to our enum.
  • value: This represents the value we want to give to our enum. This could be more than one.

Return value

An enumeration is returned with a set of related values.

Example

import Swift
// create some enumerations
enum Colors {
case RED
case GREEN
case BLUE
}
enum Fruits {
case MANGO, PINEAPPLE, ORANGE
}
enum Seasons {
case WINTER, SPRING, AUTUMN, SUMMER
}
// Print the enumerations created
print("The Primary colors are: ", Colors.RED,Colors.GREEN,Colors.BLUE)
print("Some fruits we know are:", Fruits.MANGO,Fruits.PINEAPPLE,Fruits.MANGO)
print("Some seasons are :", Seasons.WINTER, Seasons.AUTUMN, Seasons.SUMMER, Seasons.SPRING)

Explanation

  • Line 4–16: We create some enumerations in Swift.
  • Line 19–21: We printed the values present in each enum to the console.

Free Resources