首页 > 解决方案 > 用一个开关切换两个枚举

问题描述

假设我有 2 个枚举,一个是动物列表,另一个是可能的大小。

假设我想根据动物和它的大小来获得它的声音。

是否有可能以某种方式同时进行两个枚举切换?

enum Animal {
  case dog
  case cat
  case bird
}

enum Size {
  case small
  case big
}

func soundForAnimal(_ animal: Animal, size: Size) {

    switch animal, size {
        case .dog, .small:
          print ("wuuf")

        case .dog, .big:
          print("wooof")

        case .cat, .small:
          print("Miau")

        case .cat, .big:
          print("MIAAAAUU")

        case .bird, .small:
          print ("piu")

        case .bird, .big:
          print("pioo")
    }
}

上面的代码是我想要实现的示例,但我不知道如何实现。

标签: iosswiftenums

解决方案


你很亲密。使开关创建一个元组:

enum Animal {
  case dog
  case cat
  case bird
}

enum Size {
  case small
  case big
}

func soundForAnimal(_ animal: Animal, size: Size) {

    switch (animal, size) {
        case (.dog, .small):
          print ("wuuf")

        case (.dog, .big):
          print("wooof")

        case (.cat, .small):
          print("Miau")

        //and so on...
    }
}

推荐阅读