使用枚举类型检查字符串

3
我正在尝试检查类型字符串是否等于数字字符串,但我似乎无法弄清如何将类型与枚举的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")

        }
    }

}

您正在尝试将“String”与“ContentType”进行比较。传递的参数是“String”,但情况是“ContentType”。 - vadian
是的,我知道,但我不知道如何检查类型是否等于枚举值的RawValue。 - Peter Pik
由于表达式在编译时已经被计算,而且你必须考虑到 nil 的情况,因此你也可以使用字面字符串而不是枚举值。 - vadian
2个回答

3
您可以通过在 switch 中使用 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
        }
    }

}

1
你正在尝试从String类编写开关,这是不正确的。你应该更新SaveContent方法为:
if let type = ContentType(rawValue: type) {
    switch type {
    case .News:
        print("news")
    case .Card:
        print("card")

    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接