DEV Community

Cover image for Swift 101: Enumerations
Silvia España Gil
Silvia España Gil

Posted on

Swift 101: Enumerations

Hola Mundo!

Welcome to a new article in a series of Swift 101 notes 📝 I created these notes while learning the language and decided to share them because why not?

If you're new to Swift or interested in learning more about this language, I invite you to follow my series! 🙊

In my last post, I shared the third part of collections which was Tuples and Dictionaries. And this week is the time for Enumerations, one of my favourites collection types.

So, let's get to it 💪​!


As a quick refresher, "Collections" are types that store multiple values of the same type in an organized structure. These include Arrays, Sets, Tuples, and Dictionaries, which we have discussed in previous articles.

Today, we'll focus on Enumerations. While not a collection in the traditional sense, enums group related values together in a type-safe manner, making them a powerful tool for modelling sets of options or states in your code.

Think of it like a fruit basket with many fruits in it. Similarly, arrays in Swift store multiple values of the same type in an ordered list, like a line of apples, oranges, and bananas neatly arranged in your basket 🍎​🍊​🍌​

There are many types of Collections, like Arrays, Sets, Tuples and Dictionaries which we already discussed. Today, let's talk about ​​✨Enumerations​✨​.


Enumerations


Enums (short for enumerations) in Swift are a powerful type that allows you to group related values together in a type-safe way. They are commonly used to model a set of related choices or states in your code.

By default, Swift will assume that our enum is a String unless we indicate otherwise.

Here are some important characteristics and rules about Enums in Swift:

  • Fixed Set of Values: Enums define a finite set of possible values (called cases). Once an enum is defined, you cannot add or remove cases, unless you change the Enum.

  • Type Safety: Enums provide type safety by ensuring that any value associated with an enum is one of the predefined cases. This makes your code safer and easier to read.

How to declare an Enum

To declare an Enum you will have to use the enum keyword followed by the enum's name and define the possible cases inside curly braces. Each case is introduced with the case keyword.

By default, Swift will assume that our enum is a String unless we indicate otherwise.

Here's an example of how to declare and use an enum:


enum Movement {
    case forward, back, left, right
}

enum Movement {
    case forward
    case back
    case left
    case right
}
Enter fullscreen mode Exit fullscreen mode

🔎​​​Please note that you can declare it in one or many lines. 🔎​


Enum RawValue

When declaring an enum, we can decide to initialise it with an initial value. This allows the enum to work with these raw values and gives us the possibility to either use the enum case or map the values itself.

Here’s how to define and use an enum with raw values:

enum Movement: String {
    case forward = "Move Forward"
    case back = "Go Back"
    case left = "Turn Left"
    case right = "Turn Right"
}

let action = Movement.right
print(action.rawValue)
// Output: Turn Right
Enter fullscreen mode Exit fullscreen mode

When setting a type for the RawValue we can use any of the types that we have available in Swift.

enum StatusCode: Int {
    case success = 200
    case notFound = 404
    case serverError = 500
}

let code = StatusCode.notFound
print(code.rawValue) // Output: 404
Enter fullscreen mode Exit fullscreen mode

Enums Managing: Using Enums Effectively

Modifying Enum

Enums in Swift are immutable by definition, meaning once they are declared with a case, they cannot change. However, you can assign a different case to the enum type.

For example:


enum Movement {
    case forward
    case back
    case left
    case right
}

// Assign to a variable an initial case
var currentMovement = Movement.forward
// Change the variable value to another case
currentMovement = .left
Enter fullscreen mode Exit fullscreen mode

In the example, we never change the value of the enum itself, but we do change the variable's value to use another declared case.

Attempting to assign a non-existent case or trying to set a new value to an existing case results in an error:

 currentMovement = .up  
//  error: type 'Movement' has no member 'up'
// This error occurs because 'Movement' does not define a case named 'up'.

 Movement.forward = .up
// error: cannot assign to property: 'forward' is not settable
// This error occurs because enum cases are constants and cannot be reassigned.
Enter fullscreen mode Exit fullscreen mode
Accessing and using Enums

To access a specific case of an enum, you simply use the variable and the enum case as shown before. Enums in Swift are type-safe and provide a clear way to handle different states or values.

var currentMovement = Movement.forward
print(currentMovement)
// Output: forward
Enter fullscreen mode Exit fullscreen mode

Enums can be also used to execute a code depending on each case. This brings a lot of flexibility and allows us to create more complex interfaces.

switch currentMovement {
case .forward:
    print("Moving forward")
case .back:
    print("Moving back")
case .left:
    print("Turning left")
case .right:
    print("Turning right")
}
// Output: Moving forward
Enter fullscreen mode Exit fullscreen mode

Enum methods

Enums in Swift can also have methods associated with them, which allows you to define behaviours based on the enum cases. Methods inside an enum can provide additional functionality related to the enum's state.

enum AccountState {
    case active
    case onHold
    case inactive
    case deleted

    func description() -> String {
        switch self {
        case .active:
            return "Active account"
        case .onHold:
            return "Pending approval"
        case .inactive:
            return "Inactive account"
        case .deleted:
            return "Deleted account"
        }
    }

    func color() -> UIColor {
        switch self {
        case .active:
            return .green
        case .onHold:
            return .yellow
        case .inactive:
            return .gray
        case .deleted:
            return .red
        }
    }
}

// Example of using the methods
let state = AccountState.active
print(state.description())  // Output: Active account
print(state.color())        // Output: green

Enter fullscreen mode Exit fullscreen mode
  • Methods in Enums: We can define methods within an enum to encapsulate specific behaviour to the cases. The methods can use the switch statement to handle each case and provide different functionalities based on the current case.

  • Multiple Methods: We can create as many methods as needed within an enum. Each method should cover all possible cases of the enum or provide a default case to handle any unforeseen cases.

👍​By defining methods in enums, you can make your code more organized and expressive, as the enum can encapsulate both its data and behaviour cohesively.👍​


__

By using enums, we can enhance the safety and readability of our code. They provide a clear way to handle different states or values, making your code more organised and expressive.

Enums encapsulate both data and behaviour, allowing us to define methods that operate based on the enum's cases. This results in more maintainable and understandable code.

I hope this overview helps you appreciate the power of enums in Swift and helps you keep learning this amazing language!🤍​


Want to keep learning about Swift?

This a full series on Swift 101, the next chapter will be Control Flow: Loops, Conditionals and Switch in Swift, so I hope to see you there!

Remember that you can always go further into this information by checking the official documentation and courses here

If you enjoyed this, please share, like, and comment. I hope this can be useful to someone and that it will inspire more people to learn and code with Swift

Top comments (0)