Swift: Creating an Enumeration

Creating an Enumeration in Swift:

Enumerations are a data type that can be found in many popular programming languages, but Swift extends their functionality by providing features that would normally be found only in classes. Enumerations are first-class types in Swift. Let’s see how we can create an enumeration in Swift.

We’ll learn how to define and initialise an enum value in this exercise.

The enum keyword and curly braces are used to define enums:

enum dataType {
    // enum definition
} ;

To define the cases of your enum, use the case keyword:

enum CatTypes {
    case persian ;
    case maine ;
    case bengal ;
    case siamese ;
} ;

You can also make your code shorter by putting all of the cases on a single line and separating them with commas:

enum CatTypes {
    case persian, maine, bengal, siamese ;
} ;

You append the case name to an enum type value to initialise it:

var max = CatTypes.maine ;

We could use let to make the variable, max, a constant, but we’re going to change it, so we’ll use a var.

max = CatTypes.birman ; // Causes compiler error because we have not defined the case of poodle

Because the compiler recognises that max is of the CatTypes type, we can safely omit the CatTypes and use the shorter dot syntax to set the value of max:

max = .bengal ;

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: