Reputation: 1
I want to input a number as a string and am using readLine which returns a String?. Then I want to convert that inputed String to an Int which also returns an Int?. If either optional returns a nil, then print an error; otherwise, use the Int. The following code works but there has to be a better way. Any ideas?
print ("Enter number: ", terminator:"")
let number = readLine ()
if number != nil && Int (number!) != nil
{
let anInt = Int (number!)!
}
else
{
print ("Input Error")
}
Upvotes: 0
Views: 48
Reputation: 437381
You can combine the unwrapping of readLine
response and the conversion to Int
and making sure the numeric conversion succeeded into a single guard
statement, e.g.,
guard let string = readLine(), let number = Int(string) else {
print("input error")
return
}
// use `number`, which is an `Int`, here
You can obviously spin that around if you want:
if let string = readLine(), let number = Int(string) {
// use `number`, which is an `Int`, here
} else {
print("input error")
}
Upvotes: 3