Swift 表单验证 - 检查是否输入了 Int 或 String

Tom*_*Tom 2 string validation integer swift

我正在尝试验证表单以确保用户输入的是整数而不是字符串。我可以检查数字是否为整数,如下所示:

 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!


    }
Run Code Online (Sandbox Code Playgroud)

我的问题是我想确保用户没有输入任何文本、双打等。我只想要整数。以下代码不起作用,因为如果变量是整数,它的计算结果为 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)
Run Code Online (Sandbox Code Playgroud)

Gra*_*rks 5

Swift 2 改变了这一点:因为 Int("abc") 和 Int("0") 都返回 0,所以不能使用整数转换。你可以用这个:

class Validation {
    static func isStringNumerical(string : String) -> Bool {
        // Only allow numbers. Look for anything not a number.
        let range = string.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
        return (range == nil)
    }
}
Run Code Online (Sandbox Code Playgroud)

它使用decimalDigitCharacterSet,并且可以更改为使用您想要的任何字符集。

func testIsStringNumerical() {
    XCTAssertEqual(SignUpLoyaltyViewController.isStringNumerical("123"), true)
    XCTAssertEqual(SignUpLoyaltyViewController.isStringNumerical(""), true)
    XCTAssertEqual(SignUpLoyaltyViewController.isStringNumerical("12AA"), false)
    XCTAssertEqual(SignUpLoyaltyViewController.isStringNumerical("123.4"), false)
}
Run Code Online (Sandbox Code Playgroud)

这比 Regex 答案快得多。(2000 次运行,0.004s 与正则表达式 0.233s)

从设备计时