枚举不起作用,预期声明

时间:2014-12-06 04:51:15

标签: swift enumeration

我是swift的新手,我正在尝试使用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"
        }

    }

第一行我得到“Expected declaration”:

for Joseph in students.allValues

有谁知道为什么?

2 个答案:

答案 0 :(得分:1)

您已将任意代码放在enum的正文中 - 这将无效。您需要func声明或变量声明(如果它们是存储属性,甚至可能不在enum中)。用以下代码修复您的代码:

  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"
      }
      // ...
    }
  }

答案 1 :(得分:-1)

我在将现有的objC代码迁移到swift时遇到了同样的问题。

我必须做的就是将包含枚举的类(在我的例子中为`Constants.h)导入到桥接头。

希望它有所帮助。