Table of contents
1.
Introduction
1.1.
Swift Enum
1.1.1.
Syntax
2.
Creating enum variables using examples
3.
Allocating values to enum variables
3.1.
Example
3.1.1.
Output
4.
Switch Statements in the enumeration
4.1.
Output
5.
Classification
6.
Enum raw values 
6.1.
Example
6.2.
Output
7.
Iterations in enum cases.
7.1.
Output
8.
Recursive Enumerations
8.1.
Output
9.
Frequently Asked Question
9.1.
What are enums in Swift?
9.2.
What is the enum value type in Swift?
9.3.
Why do we use enums in Swift?
9.4.
Can enum have functions in Swift?
10.
Conclusion
Last Updated: Mar 27, 2024

Swift enum

Author Neha kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Swift is Apple's user-friendly and powerful programming language. It is used to create apps for various platforms, including iOS, macOS, and watchOS. In this article, you'll learn some programming basics while using the Swift programming language in a modern, user-friendly environment.

We will discuss the swift enum and its classification.This article will look at the basic definition and use of enumeration.

So, Let's get started! 

Swift Enum

An enumeration is a client characterized information type which comprises a set of related values. Identification in Swift additionally looks like the design of C and Objective C. Its pronunciation in a class and its values are obtained through that class's occurrence. Starting part value is characterized by utilizing enum initializers. Its usefulness is the addition stretched out by ensuring standard convention usefulness.

Syntax

Enumerations are made to use with the enum keyword and then putting the rest of the data or information inside a pair of braces:

enum enumname{
//values initialized here
}

 

For instance, we can explain this with the names of months as described below-

Enum MonthsofaYear{
case January 
case February
case March
}

Creating enum variables using examples

Enum is a data type so that we can make factors or variables of the enum type. For instance,

var present month: MonthsofaYear

 

Here, the current Month is a MonthsofaYear type variable. The values it can have are (January, February, March, etc.) present inside the enum.

Allocating values to enum variables

We utilize the enum name and the documentation to provide values to an enum variable. For instance,

// assign April to the present month variable
var present month = Month.April

 

Here, we have assigned the value April to the enum variable

Example

// define enum 
enum Month {
  
  // define values
  case January, February, March, April.
}


// create enum variable
var presentMonth: Month


// assign value to enum variable
presentMonth = Month.april
print("Present Month:", presentMonth)

Output

Present Month: April.

Switch Statements in the enumeration

'Switch' statements additionally allow the multi-way choice. A single variable reaches a specific time because of the predefined condition. The default case in the switch statement is utilized to trap vague claims.

enum Month {
   case January
   case February
   case March
   case April
}


var present = Month.February
present = .February
switch present {
   case .January:
      print("Jan is is")
   case .February:
      print("Feb it is")
   case .March:
      print("March it is")
   case .April:
      print("April it is")
   
}

Output

Feb it is.

 

In the code, a Month is being defined as an enumeration name. Then its members like 'January,'' February,' March,'' April' are limited, which ascertains class' Month. Then a member February is assigned to a present variable. Now switch case will get the values accordingly, February, and it will relate to the specific line of code. The result gets displayed as 'Feb it is'. Similarly, all other members can also be accessed using the switch cases and assigning members initially to fetch the desirable output

Classification

Enumeration consists of two types  

1.associated values

2.raw values.

 

These two classifications can be distinguished as such:

Enum raw values 

We use the rawValue property to access the raw value of an enum. For examples:

// accessing raw value 
Size.small.rawValue

 

Here, we access the value of the medium case.

Example

enums With Raw Values

enum Size : Int{
  case small = 8
  case medium = 10
  case large = 12
}


// access raw value of python case
var result = Size.small.rawValue
print(result)

Output

10

 

In this example, an enum named Size has a raw value of Int type. 

Iterations in enum cases.

Iterations in enums can be used in the same way. To iterate or create a looping statement for making a particular statement repeatedly by reducing the complexity in the number of lines of codes.

In Swift, we use the CaseIterable protocol to iterate over an enum. For example,

enum Month: caseIterable {
  ...
}

 

Here, you can use the allCases property to loop through each case of an enum.

for presentMonth in Month.allCases {
   ...
}

 

Iterations:

// conform Languages to caseIterable 
enum Month: CaseIterable {
  case january, february, march, april
}


// for loop to iterate over all cases
for presentMonth in Month.allCases {
  print(presentMonth)
}

Output

January
February
march
April

Recursive Enumerations

A recursive enumeration is a specification with one more example of the enumeration as the corresponding value for at least one of the enumeration cases. You show that a specification case is recursive by composing indirect before it, which advises the compiler to embed the fundamental layer of indirection.

A recursive function is also an easy-to-use way to use data that consists of a recursive structure. For example:

func calc(_ expression: ArithmeticExpression) -> Int {
    switch expression {
    case let .number(value):
        return value
    case let .addition(left, right):
        return calc(left) + calc(right)
    case let .multiplication(left, right):
        return calc(left) * calc(right)
    }
}


print(calc(product))
// Prints "18"

Output

18

 

This function calculates a plain number by essentially returning the corresponding value. It calculates an option or duplication by calculating the articulation on the left-hand side, the expression on the right-hand side, and afterward adding or increasing them.

Frequently Asked Question

What are enums in Swift?

In Swift, an enum (short for specification) is a user-defined data type with a fixed arrangement of corresponding values.

What is the enum value type in Swift?

Types in Swift can be categorized as one of two classes: first, "value types," where each instance keeps an exceptional duplicate of its information, typically characterized as a struct, enum, or tuple. The second is "reference types," where models share a single copy of the information, and the sort will be characterized as a class.

Why do we use enums in Swift?

A list characterizes a typical sort for a gathering of related values and helps you work with those qualities in a kind, safe manner inside your code. Specifications in Quick are significantly more adaptable and don't need to offer a benefit for each instance of the enumeration.

Can enum have functions in Swift?

You cannot make a function available to one case of an enum only. Any function in an enum is open to every point of the enum. 

Conclusion

Swift enums can be a robust method for working on your code. Here, we covered the syntax of enums and how to characterize them, switch statements in enums, and how to involve them in switch articulations. We likewise described CaseIterable as a kind that gives an assortment of the values of the enumerations. We covered enum values (raw and associated values) and how to utilize them in our codebase. Also, see the iterative functions and recursive functions along with enums are also explained.

We hope that this blog has helped you enhance your knowledge of Swift enum and if you would like to learn more, check out our articles on Strings in Swiftt , The Definitive Swift Tutorial for Beginnerswhy iOS & OS X Developers are choosing Swift? and which is better to learn? iOS or Android?. Do upvote our blog to help other ninjas grow, and head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.

Live masterclass