Enum I
Definition and pros.
Enum I
Definition and pros.
0
0
Checkbox to mark video as read
Mark as read

What is an enum?

An enum is a type of variable that only stores the values that have been previously defined. Let’s see how to create one.

enum OrderStatus {
    case preparing
    case sent
    case outForDelivery
    case delivered
}

This type of variable is used like any other, except that the values we can assign are exclusively the cases we’ve defined.

var pedroOrderStatus: OrderStatus = OrderStatus.sent
var andreaOrderStatus: OrderStatus = OrderStatus.preparing

The big advantage of this type of variable is that unlike using, for example, String variables where each developer might use a different value ("Sent", "SENT", "sent", ...), which would cause issues when comparing values, an enum only allows assigning the predefined cases.

Using enum in a switch

Since an enum is composed of "cases," it is the perfect type of variable to use in a switch. Let’s look at an example.

// Declare our enum
enum OrderStatus {
    case preparing
    case sent
    case outForDelivery
    case delivered
}

// Declare the variable that will store Pedro's order status
var pedroOrderStatus: OrderStatus = OrderStatus.sent

// Check the order status and display a message in the console
switch pedroOrderStatus {

case .preparing:
    print("The order is being prepared")

case .sent:
    print("The order has been sent")

case .outForDelivery:
    print("The order is out for delivery")

case .delivered:
    print("The order has been delivered")
}

// The console shows: The order has been sent

As you can see, there’s no need to write OrderStatus.sent in each case of our switch; you can simply write .sent, as Xcode infers the type of pedroOrderStatus from its declaration.

In fact, this can be done in any situation where Xcode clearly knows the type of the enum.

Let’s look at some examples of what you can and cannot do.

var pedroOrderStatus: OrderStatus = .sent // Correct, because the type is specified before the = symbol
var andreaOrderStatus = OrderStatus.sent // Correct, because the type is specified after the = symbol

if andreaOrderStatus == .sent {  // Correct, because the type of "andreaOrderStatus" was specified earlier
    // ...
}

var teresaOrderStatus = .sent // INCORRECT. The type ".sent" is not indicated as belonging to "OrderStatus" or any other enum.

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy