0

Here is my code, When I input 20 as below. It shows an error. See the attach file

enum GuessNumberGameError: Error {
    case wrongNumber
}
class GuessNumerGame {

 var targetNumber = 10

 func guess (number : Int)  throws
    {
        guard number == targetNumber  else
        {
            print(number)
            throw GuessNumberGameError.wrongNumber
        }
        print("Guess the right number : \(targetNumber)")
    }
}

let test = GuessNumerGame()
try test.guess(number: 20)

enter image description here

Rohit Parihar
  • 352
  • 1
  • 7
  • 14
Jim
  • 13
  • 2
  • See https://stackoverflow.com/q/48082571/1187415 about “try without do/catch at the top-level”. – Martin R Nov 12 '19 at 10:46

2 Answers2

0
let test = GuessNumerGame()
do
{
  try test.guess(number: 20)
}catch let error
 {
 print("error --\(error)")
 }

Your program OutPut

20
error --wrongNumber
Lalit kumar
  • 1,797
  • 1
  • 8
  • 14
0

If you are just using this to explore throwing errors, then the answer above is all you need. But if not...

Errors are usually thrown to represent failed operations, not to return the success/failure of a test. In which case I'd refactor so that the function has a return type that shows the outcome of the test - this will be easier and more elegant to handle in your code. Below returns a Bool type, but you could extend this to return a Result<Int> type if you wanted to still use your GuessNumberGameError enum.

func guess (number : Int) -> Bool {
  if number = targettNumber {
    print("You guessed right: \(number)")
    return true
  } else {
    print("Wrong number")
    return false
  }
}

then you can either capture the result:

let result = test.guess(number:20)

or ignore it if the printed text is enough

let _ = test.guess(number:20)
flanker
  • 3,840
  • 1
  • 12
  • 20