Swift Program to Lookup enum by String value


An enumeration or enum is a user-defined data type which holds a set of related values. It is defined by using the enum keyword. It is also known as an enum case because it uses case keywords to declare values inside it. In Swift, we are allowed to create an enum by the string value.

Syntax

enum nameOfEnum: Type {
   case value1
   case value2
   case value3
}
Let enumVariable = value

Here, nameOfEnum represents the name of the enum, value1, value2, etc are values defined in the enum and enumVariable is the variable of an enum type and can store only those values present inside the given enum.

Algorithm

  • Step 1 − Create an enum of string type.

  • Step 2 − Assign the values in the enum using the case statement.

  • Step 3 − Now create a function to get values from the enum.

  • Step 4 − Create a variable with a. value

  • Step 5 − Check if the value is present in the variable or not by calling the above function.

  • Step 6 − Display the output

Example 1

In the following Swift program, we will lookup an enum by the string value. So first we will create an enum of string type with 5 values. Then we create a variable of enum type and then assign the enum value to the variable using ProLanguages.Java and print the output.

import Foundation
import Glibc

enum ProLanguages: String {
   case Swift
   case Java
   case Python
   case Perl
   case CSharp
}

// Create variable of enum
let resValue : ProLanguages

// Assigning value to the variable
resValue = ProLanguages.Java

print("Best programming Language is:", resValue)

Output

Best programming Language is: Java

Example 2

In the following Swift program, we will lookup enum by the string value. So first we will create an enum of string type with 6 values. Then create a function which takes an input string and tries to match it with the cases present in the given enum using rawValue initializer. If the match is found in the given enum, then it will return the value, otherwise return nil.

import Foundation
import Glibc

enum geomertyBox: String {
   case Pencil
   case Pen
   case Sharpener
   case Eraser
   case Glue
}

func getElements(from str: String) -> geomertyBox? {
   return geomertyBox(rawValue: str)
}

let inputItem = "Pen"
if let result = getElements(from: inputItem) {
   print("Item found in the geomertyBox: \(result.rawValue)")
} else {
   print("Try again!!")
}

Output

Item found in the geomertyBox: Pen

Conclusion

So this is how we can lookup an enum by the string value. In the enum, you can declare as much value as you want. Also, you can assign raw values to the enum values. You can also iterate through an enum using a for-in loop. It allows you to work with values in a type-safe way. It is generally used when the developer has multiple options to encode.

Updated on: 14-Jun-2023

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements