How do we set a enum based on whether that value exist within an array? I am getting back error "Reference to member dog cannot be resolved without a contextual type". Same issue with cat.
Where i set my print statements, i want to be able to call specific methods, but im having trouble understanding what im doing wrong. Any pointers?
enum AnimalType: String {
case cat = "cat"
case dog = "dog"
}
func checkType() {
let animals = ["lion", "cat", "horse", ""]
var animalType: AnimalType?
///Check if animals array contains a value that is the same as our enum
if animals.contains(where: {$0 == animalType?.rawValue }) {
if let animalType = animalType?.rawValue {
switch animalType {
case .cat:
print("This is cat")
case .dog:
print("This is dog")
}
}
}
}
>Solution :
The problem is in this line: if let animalType = animalType?.rawValue. animalType?.rawValue gives you a String associated with the enum case, but you’re interested in the case itself. This should work:
if let animalType = animalType {
switch animalType {
case .cat:
print("This is cat")
case .dog:
print("This is dog")
}
}
I assume you initialize let animalType: AnimalType? before using it the way you want, otherwise your code doesn’t compile even with the fix. For instance, a piece of code that compiles and works (though, not necessarily does what you want – you didn’t explain that part):
enum AnimalType: String, CaseIterable {
case cat = "cat"
case dog = "dog"
}
func checkType() {
let animals = ["lion", "cat", "horse", ""]
guard let animalString = animals.first(where: { AnimalType.allCases.map { $0.rawValue }.contains($0) }),
let animal = AnimalType(rawValue: animalString) else {
return
}
switch animal {
case .cat:
print("This is cat")
case .dog:
print("This is dog")
}
}
