每当存在错误(存储在变量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
设置为"missing email address"
。问题所在的代码部分在这里:
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 {
}
}
}
答案 0 :(得分:4)
查看 String 和 NSString 的rangeOfString。第一个返回 Range?。第二个返回 NSRange 。您的变量被推断为 NSString ,因此测试返回 NSRange ,而不是可选的Range,并且永远不会为nil。将变量类型更改为String以获得所需的行为。
这也应该有效:
if (errorString!.rangeOfString("missing username").toRange() != nil) {
errorString = "missing email address"
}