使用枚举检查字符串

时间:2016-04-25 10:22:27

标签: ios swift enums

我试图检查类型字符串是否等于num字符串,但是我似乎无法弄清楚我是如何根据枚举的rawValues检查类型的。到目前为止我已经做到了这一点:

但是我不断获得Enum case News not found in type String

enum ContentType: String {

    case News = "News"
    case Card = "CardStack"

    func SaveContent(type: String) {

        switch type {
            case .News:
                print("news")
            case .Card:
                print("card")

        }
    }

}

2 个答案:

答案 0 :(得分:1)

您正在尝试从String类中编写一个不正确的开关。您应该使用以下命令更新SaveContent方法:

if let type = ContentType(rawValue: type) {
    switch type {
    case .News:
        print("news")
    case .Card:
        print("card")

    }
}

答案 1 :(得分:1)

您可以通过在交换机中使用enum的原始值来解决此问题:

enum ContentType: String {

    case News = "News"
    case Card = "CardStack"

    func SaveContent(type: String) {
        switch type {
        case ContentType.News.rawValue:
            print("news")
        case ContentType.Card.rawValue:
            print("card")
        default:
            break
        }
    }

}