【发布时间】:2015-02-02 22:08:40
【问题描述】:
我正在尝试验证表单以确保用户输入的是整数而不是字符串。我可以检查数字是否为整数,如下所示:
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!
}
我的问题是我想确保用户没有输入任何文本、双打等。我只想要整数。以下代码不起作用,因为如果变量是整数,它的计算结果为 true。如果变量不是整数,我应该使用什么代码来评估?
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)
})
alertController.addAction(alertAction)
presentViewController(alertController, animated: true, completion: nil)
【问题讨论】:
标签: string validation swift integer