Tom Tom - 1 year ago 110
Swift Question

Swift Form Validation - Check if Int or String has been entered

I am trying to validate a form to make sure the user has entered an integer number and not a string. I can check if the number is an integer as follows:

var possibleNumber = timeRetrieved.text
convertedNumber = possibleNumber.toInt()
// convertedNumber is inferred to be of type "Int?", or "optional Int"

if convertedNumber != nil {

println("It's a number!")

totalTime = convertedNumber!


My problem is I want to make sure the user has not entered any text, doubles etc. I only want integer numbers. The following code does not work because it evaluates true if the variable is an integer. What code should I use to evaluate if variable is not an integer?

if convertedNumber != nil {

let alertController = UIAlertController(title: "Validation Error", message: "You must enter an integer number!", preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Destructive, handler: {(alert : UIAlertAction!) in
alertController.dismissViewControllerAnimated(true, completion: nil)
presentViewController(alertController, animated: true, completion: nil)

Answer Source

If the number the user has entered is not an integer, convertedNumber will be nil. Just add an else clause in which you can show the alert.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download