【问题标题】:Access enum value defined in another class访问另一个类中定义的枚举值
【发布时间】:2015-11-07 08:09:02
【问题描述】:

我有一个枚举定义如下,

class Question: NSObject {
    enum Type:String {
        case Text = "TEXT"
        case Image = "IMAGE"
    }
    /**!!!Here I can access it like this!!!*/
    var type = Type.Text
}

但是,在另一个类中,

class MyViewController: UIViewController {
    /**!!!This doesn't work!!!*/
    var type = Question.Type.Text
}

是不是我做错了什么?

谢谢

【问题讨论】:

  • 我不知道具体原因,但您不能将枚举命名为 Type。将其更改为其他内容,它将起作用。
  • 看起来你重新实现了现有类型Type,例如尝试使用enum Type2:String 来测试它
  • @Rog 谢谢,终于明白了。苹果太可笑了。

标签: ios swift cocoa-touch enums


【解决方案1】:

除了上述内容(重命名您的枚举!),您只需在 Question 类之外声明枚举。您不必为此创建新文件(尽管您可以根据需要),只需将其放在您的类上方,如下所示:

enum QuestionType: String {
    case Text  = "TEXT"
    case Image = "IMAGE"
}

class Question: NSObject {
    //...
}

现在您可以在 MyViewController 类中使用 QuestionType 枚举。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多