Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift: Set a enum based on value from array

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")
            }
        }
        
    }
}

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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")
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading