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.
1 2 3 |
enum Name { // enumeration definition } |
For Example:
1 2 3 4 |
enum Gender{ case male case female } |
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 :
1 2 3 4 5 6 |
switch gender{ case .male: print("Gender is male") case .female: print("Gender is female") } |
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:
1 2 3 4 5 |
enum Gender{ case male = 1 case female } |
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:-
1 2 3 4 5 6 7 |
enum Number: Int{ case one = 1 case two = 2 case three } |
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:
1 2 3 4 5 6 7 8 |
enum Days: String{ case Monday case Tuesday func getDay() -> String{ return self.rawValue } } |
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.