您好我有一个简单的switch case语句,它有一个错误"在预期返回的函数中缺少返回' String'"
我所能看到的就是我要归还一切。没有if语句,因此它不能成为缺失的回报。
enum Sign { case rock, paper, scissors }
func detectWinner(player: Sign, bot: Sign) -> String{
switch player{
case .rock:
switch(bot){
case .rock: return "You Tied"
case .paper: return "You Lost"
case .scissors: return "You Won"
}
case .paper:
switch(bot){
case .rock: return "You Won"
case .paper: return "You Tied"
case .scissors: return "You Lost"
}
case .scissors:
switch(bot){
case .rock: return "You Lost"
case .paper: return "You Won"
case .scissors: return "You Tied"
}
}
}
答案 0 :(得分:4)
正如其他人所说,你的代码应该编译,因为你彻底处理了所有的switch语句。尝试清洁和重建。
顺便说一下,这似乎很好地使用了带有元组的switch语句:
enum Sign { case rock, paper, scissors }
func detectWinner(player: Sign, bot: Sign) -> String{
switch (player, bot){
case (.rock, .rock): return "You Tied"
case (.rock, .paper): return "You Lost"
case (.rock, .scissors): return "You Won"
case (.paper, .rock): return "You Won"
case (.paper, .paper): return "You Tied"
case (.paper, .scissors): return "You Lost"
case (.scissors, .rock): return "You Lost"
case (.scissors, .paper): return "You Won"
case (.scissors, .scissors): return "You Tied"
}
}
这比嵌套的switch语句更容易阅读和维护。 (它为我建造,至少在游乐场中建造)
答案 1 :(得分:0)
Xcode很奇怪。程序关闭修复了这个奇怪的错误。