每当存在存储在变量errorString中的错误时,我想检查错误是否包含字符串"missing username"。如果errorString确实有字符串,则将"missing username"设置为errorString。但是,即使"missing email address"没有errorString,也会将"missing username"设置为errorString。例如,即使"missing email address",它仍然将errorString = 2015-09-08 11:44:39.937 ParseStarterProject-Swift[15182:93559] [Error]: invalid email address (Code: 125, Version: 1.8.2)设置为errorString。问题所在的代码部分如下:

if (errorString?.rangeOfString("missing username") != nil) {
    errorString = "missing email address"
}

其余相关代码如下:
@IBAction func signUp(sender: AnyObject) {
    let user = PFUser()
    user["firstName"] = firstName.text
    user["lastName"] = lastName.text
    user.email = emailAddress.text
    user.password = password.text
    user.username = emailAddress.text

    user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in
        if let error = error {
            var errorString = error.userInfo?["error"] as? NSString
            errorString = String(errorString!)
            print(errorString)

            if (errorString?.rangeOfString("missing username") != nil) {
                errorString = "missing email address"
            }

            let alertController = UIAlertController(title: "", message: "\(errorString!)", preferredStyle: UIAlertControllerStyle.Alert)
            alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
                println("Handle Ok logic here")
            }))
            self.presentViewController(alertController, animated: true, completion: nil)
        } else {

        }
    }
}

最佳答案

看看字符串和nsstring的rangeofstring。第一个返回范围?。第二个返回nsrange。您的变量被推断为nsstring,因此测试返回nsrange,而不是可选范围,并且永远不会为零。将变量类型更改为字符串以获得所需的行为。
这也应该有效:

if (errorString!.rangeOfString("missing username").toRange() != nil) {
    errorString = "missing email address"
}

10-07 14:27