【问题标题】:Check strings using enums使用枚举检查字符串
【发布时间】:2016-04-25 10:22:27
【问题描述】:

我正在尝试检查类型字符串是否等于 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")

        }
    }

}

【问题讨论】:

  • 您正在尝试将StringContentType 进行比较。传递的参数是String,但大小写是ContentType
  • 是的,我知道,但我只是不知道如何检查类型是否等于枚举值的 RawValue。
  • 由于无论如何表达式都是在编译时计算的,并且您必须考虑 nil 的情况,您也可以使用文字字符串而不是枚举值。

标签: ios swift enums


【解决方案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
        }
    }

}

【讨论】:

    【解决方案2】:

    您正在尝试从您的 String 类编写一个不正确的开关。您应该更新 SaveContent 方法:

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

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多