Enumerations in swift

Updated 29 July 2022

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.

author
. . .

Leave a Comment

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


Be the first to comment.

Start a Project


    Message Sent!

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

    Back to Home