Check Mobile App
Read now
Start a Project

Enumerations in swift

Save

An enumeration is a user-defined data type that consists of a set of related values. We use enumerations to define your own kind of value in Swift. An enum is a data type that consists a set of named values, called members. We use keyword enum to define the enumerated data types.

Enums are much more flexible and do not have to provide a value for each case of the enumeration. If a value is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.

Syntax:

We introduce enumerations with the “enum” keyword and place their definition within a pair of braces.

For Example:

The defined values in an enumeration are its enumeration cases. We always use the case keyword to introduce new enum cases.

We can now define a variable as an enumeration case like:

var gender: Gender = Gender.male or

var gender = Gender.male

Switch Statement using enums :

We do not need to define a default case for enum switch statement as we have used all the possible enum members. If we do not check all the enum members, then we need a default case.

Enums with User Defined Values:

Enums can not have a user-defined value until and unless it has a raw type.

Example:

This code in the example will throw an error since we haven’t defined a raw type to enum. To define a value to enum, it must have a raw type, for example:-

This now enumerates the values and assigns numbers. One with 1 and genres, Two with 2 and so on. If we use integers for raw values, they auto-increment from the previous value if no value is specified.

Enums with methods:

Enums can have methods that can be used on enum cases. For example:

We can call this function like Days.Monday.getDay, which will return rawValue of case Monday, means output: Monday.

Conclusion:

In this blog, we learned about enums. Enums can have methods, subscripts, and computed properties, but enums cannot have stored properties. To know more about enums, you can look here.

You can read more of my blogs from this link.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

css.php

When I think in getting solutions for my Ecommerce Platform, I think of Webkul. They have been such a blessing in our business. We have spent thousands of dollars in support and modules from them. We love their support team. They work very closely with us, and they always go the extra mile when we need help.

Michael Urresta

Michael Urresta

Talk to Sales

Global

Live Chat
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home