【问题标题】:Swift - Nested enums - how to perform same action on all nested enums with associated values?Swift - 嵌套枚举 - 如何对所有具有关联值的嵌套枚举执行相同的操作?
【发布时间】:2021-02-04 20:12:48
【问题描述】:

我想打印嵌套枚举的原始值。例如,如果我有一个包含多个案例的顶级食品枚举(为简单起见,我们只说两个:水果,蔬菜),每个都是字符串枚举(水果:字符串,蔬菜:字符串等),有没有办法打印内部关联值而不在顶级枚举中执行 switch 语句?

我当前的代码如下。如您所见,我添加到 Food 中的案例越多,var description 中的冗余代码就越多。我想为所有打印内部枚举的 rawValue 的情况编写一个动作。

没有开关可以吗?

enum Foods {
    case fruit(Fruit)
    case veggie(Vegetable)
 
    var description: String { // this is what I'd like to replace 
         switch self {
         case .fruit(let type):
             return type.rawValue // since every case will look like this
         case .veggie(let type):
             return type.rawValue
         }
    }
}

enum Fruit: String {
    case apple = "Apple"
    case banana = "Banana"
}

enum Vegetable: String {
    case carrot = "Carrot"
    case spinach = "Spinach"
}

【问题讨论】:

    标签: swift enums computed-properties associated-value


    【解决方案1】:

    没有开关可以吗?

    不,目前不可能。


    解决方法:我注意到您的枚举案例名称存在一种模式。每个的原始值都是案例名称i.e. case apple = "Apple" 的大写版本。如果此模式始终成立,您可以使用以下代码:

    var description: String { ("\(self)".split(separator: ".").last?.dropLast().capitalized)! }
    

    这将产生:

    print(Foods.fruit(.apple).description) // Apple
    

    【讨论】:

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