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?