Search code examples
swiftenumeration

enum not working, expected declaration


I'm new to swift and am trying to use enumeration:

    enum students : String {
        case Joseph = "Joseph", Matt = "Matt", Cody = "Cody", Rick = "Rick"

        static let allValues = [Joseph, Matt, Cody, Rick]

        for Joseph in students.allValues{
        studentPic.image = UIImage(named: "joseph.gif")
        studentLabel.alpha = 1
        studentLabel.text = "Joseph is an A+ student"
        }
        for Matt in students.allValues{
        studentPic.image = UIImage(named: "matt.gif")
        studentLabel.alpha = 1
        studentLabel.text = "Matt is a B+ student"
        }
        for Cody in students.allValues{
        studentPic.image = UIImage(named: "cody.gif")
        studentLabel.alpha = 1
        studentLabel.text = "Cody is a C+ student"
        }
        for Rick in students.allValues{
        studentPic.image = UIImage(named: "rick.gif")
        studentLabel.alpha = 1
        studentLabel.text = "Rick is a D+ student"
        }

    }

I get "Expected declaration" for the first line :

for Joseph in students.allValues

Does anyone know why?


Solution

  • You've put arbitrary code in the body of an enum - that won't work. You need either func declarations or variable declarations (although perhaps not even in a enum if they are stored properties). Fix your code with:

      enum students : String {
        case Joseph = "Joseph", Matt = "Matt", Cody = "Cody", Rick = "Rick"
    
        static let allValues = [Joseph, Matt, Cody, Rick]
    
        func doSomething () {
          for Joseph in students.allValues{
            studentPic.image = UIImage(named: "joseph.gif")
            studentLabel.alpha = 1
            studentLabel.text = "Joseph is an A+ student"
          }
          // ...
        }
      }