-5

I have the following code to check if a number is a prime number or not:

var isPrime = true
var number = "Four"
var i = 2
var numInt = Int(number)

if numInt == nil {
    print("Sorry, this is not a valid number")
} else {
    while i < number {
        if number % i == 0  {
            isPrime = false
        }
        i += 1
    }
}

I'm trying to avoid crashes so want to print an error message if the number is not an actual integer. So in the above, for example, if user enters a number as a string, it should print the error.

numInt is printing as nil here, but the app crashes because even though that part of the if statement is true, it seems to move onto the else statement and tries to run it using the string. How do I avoid that second part being run?

Steve Ives
  • 7,894
  • 3
  • 24
  • 55
DevB1
  • 1,235
  • 3
  • 17
  • 43

1 Answers1

0

It does not crash, it doesn't even compile. The following is probably what you want:

var isPrime = true

var number = "Four"

var i = 2

if let numInt = Int(number) {
    while i < numInt {
        if numInt % i == 0  {
            isPrime = false
        }
        i += 1
    }
} else {
    print("Sorry, this is not a valid number")
}

This will print "Sorry, this is not a valid number". If you set var number = "123" it will run the loop.

fphilipe
  • 9,739
  • 1
  • 40
  • 52