gpt4 book ai didi

xcode - rangeOfString 每次都返回不为零

转载 作者:可可西里 更新时间:2023-11-01 00:52:28 25 4
gpt4 key购买 nike

每当有错误存储在变量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 {

}
}
}

最佳答案

查看 StringNSString 的 rangeOfString。第一个返回 Range?。第二个返回 NSRange。您的变量被推断为 NSString,因此测试返回 NSRange,而不是可选范围,并且永远不会为零。将变量类型更改为字符串以获得所需的行为。

这也应该有效:

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

关于xcode - rangeOfString 每次都返回不为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32449062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com