Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use switch with enum for string

Tags:

swift

Sorry for the extremely basic question, but I want to figure out how to use a switch statement with cases that check if it's a certain string.

For example if I have an AnimalType enum and then I have an animal struct:

enum AnimalType: String {
   case Mammal = "Mammal"
   case Reptile = "Reptile"
   case Fish = "Fish"
}

struct Animal {
   let name: String
   let type: String
}

If I want to go through a list of Animals and then have a switch statement, how would I match the Animal.Type string to the enum? I don't want to change the Animal struct to let type: AnimalType either.

switch Animal.type {
case :
...// how do I match the string to the enum?
like image 796
user3628240 Avatar asked Mar 18 '18 06:03

user3628240


People also ask

Can we use switch with enum?

You definitely can switch on enums.

Can we use enum as string?

In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member. While string enums don't have auto-incrementing behavior, string enums have the benefit that they “serialize” well.

Can we use switch with string?

Yes, we can use a switch statement with Strings in Java.


Video Answer


2 Answers

enum Command: String {
   case Mammal = "Mammal"
   case Reptile = "Reptile"
   case Fish = "Fish"
}

let command = Command(rawValue: "d")

switch command {
case .Mammal?:
    print("Mammal")
case .Reptile?:
    print("second")
case .Fish?:
    print("third")
case nil:
    print("not found")
}
// prints "not found"
like image 99
Ferrakkem Bhuiyan Avatar answered Sep 28 '22 22:09

Ferrakkem Bhuiyan


You can create an animal type from string rawValue and switch on that: But first I'd change the cases to lowercase, thats the preferred style in Swift.

func checkType(of animal: Animal) {
    guard let animalType = AnimalType(rawValue: animal.type) else {
        print("Not an animal type")
        return
    }
    switch animalType {
    case .mammal: break
    case .reptile: break
    case .fish: break
    }
}

Alternatively, you can also switch on the string and compare if it matches any of your AnimalType rawValues:

func checkType(of animal: Animal) {
    switch animal.type {
    case AnimalType.mammal.rawValue: break
    case AnimalType.reptile.rawValue: break
    case AnimalType.fish.rawValue: break
    default:
        print("Not an animal type")
        break
    }
}
like image 25
Glaphi Avatar answered Sep 28 '22 23:09

Glaphi