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?
You definitely can switch on enums.
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.
Yes, we can use a switch statement with Strings in Java.
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"
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With