Ios 用一个开关切换两个枚举
假设我有两个枚举,一个是动物列表,另一个是它可能的大小 比如说,我想根据动物和它的大小,通过一个函数得到它的声音 是否可以以某种方式同时进行两个枚举切换Ios 用一个开关切换两个枚举,ios,swift,enums,Ios,Swift,Enums,假设我有两个枚举,一个是动物列表,另一个是它可能的大小 比如说,我想根据动物和它的大小,通过一个函数得到它的声音 是否可以以某种方式同时进行两个枚举切换 enum Animal { case dog case cat case bird } enum Size { case small case big } func soundForAnimal(_ animal: Animal, size: Size) { switch animal, size {
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...
}
}
你很接近。使开关创建一个元组:
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...
}
}
你差点就成功了。改为编写
开关(动物,大小)
,和外壳(.dog,.small):
。您刚才缺少了用于切换元组的括号。谢谢,您的评论非常有用!Swift语法和其他许多语法都记录在Swift语言指南中。强烈推荐阅读。你差点就成功了。改为编写开关(动物,大小)
,和外壳(.dog,.small):
。您刚才缺少了用于切换元组的括号。谢谢,您的评论非常有用!Swift语法和其他许多语法都记录在Swift语言指南中。强烈推荐阅读。谢谢你的回答和Larme的评论非常有用!谢谢你的回答和Larme的评论非常有用!