ios - 用一个开关切换两个枚举
问题描述
假设我有 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")
}
}
上面的代码是我想要实现的示例,但我不知道如何实现。
解决方案
你很亲密。使开关创建一个元组:
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...
}
}
推荐阅读
- linux - 使用 bash 重命名多个目录中的文件
- python - 有没有办法获得最新的chrome版本?
- php - Wordpress get_post_meta 没有显示数据库中的所有元数据?
- c++ - 使用 QAbstractTableModel 的 QML 图表不会动态更新
- python - pymodbus 的问题
- java - Java 遍历类字段以创建其他类
- python - 有没有办法保持索引嵌套字典,直到找到一个字符串值?
- c# - IQueryable 作为列表
- swagger - 标签 $ref 不显示内容 openapi3.0
- python - AssertionError: False 不正确,测试每次都失败是因为那个原因?