Need clarification for switch statement - Swift: Rock-paper-scissors

Hey guys, my code perfectly works when I follow the guide. I just don’t understand how “It’s a tie” works here. Sorry if it’s a stupid question :smiley:

In my opinion we should include somewhere that when
if userChoice == compChoice {
decision = “It’s a tie”
}

But the code works perfectly without it. How does it understand that decision should be Tie when the choices are same?

func getUserChoice(userInput: String) → String {
if userInput == “rock” || userInput == “scissors” || userInput == “paper”{
return userInput
} else {
return “You can only enter rock, paper, or scissors. Try again.”
}
}

func getComputerChoice() → String {
let randomNumber = Int.random(in:0…2)
switch randomNumber {
case 0:
return “rock”
case 1:
return “paper”
case 2:
return “scissors”
default:
return “Something went wrong.”
}
}

func determineWinner(_ userChoice: String, _ compChoice: String) → String {
var decision = “It’s a tie”
switch userChoice {
case “rock”:
if compChoice == “paper” {
decision = “The computer won”
} else if compChoice == “scissors” {
decision = “The user won”
}
case “paper”:
if compChoice == “rock” {
decision = “The user won”
} else if compChoice == “scissors” {
decision = “The computer won”
}
case “scissors”:
if compChoice == “rock” {
decision = “The computer won”
} else if compChoice == “paper” {
decision = “The user won”
}
default:
print(“Something went wrong”)
}
return decision
}

let userChoice = getUserChoice(userInput: “paper”)

let compChoice = getComputerChoice()

print(“You threw (userChoice)”)
print(“The computer threw (compChoice)”)
print(determineWinner(userChoice, compChoice))

In the determineWinner function, you are initializing decision in the first line.

var decision = "It's a tie"

Suppose user and computer both chose “paper”. The second case i.e. case "paper": will match. However, neither the if condition nor the else if condition will be true. You exit the switch statement without doing anything. Immediately after the switch statement, you return decision so the initial value of "It's a tie" will be returned.
The default in the switch statement isn’t executed because you did match one of the cases. Even though one of the cases is matched, no conditional is true when computer choice is the same as user choice. So, nothing happens and the initial value of decision persists. The default "Something went wrong" would only print when the user chose something other than “rock” or “paper” or “scissors”.

2 Likes

Thank for clarification. Now it’s clear :bowing_woman:

1 Like