第一次在Swift中编码。我一直在获得"可选类型的值'字符串?'没有打开"我声明if
语句条件的行上的错误。我究竟做错了什么?
@IBAction func registerButtonTapped(sender: AnyObject) {
let userName = userNameTextField.text;
let userPhoneNumber = userPhoneNumberTextField.text);
let userPassword = userPasswordTextField.text;
let userReenterPassword = userReenterPasswordTextField.text;
// Check for empty fields
if(userName.isEmpty || userPhoneNumber.isEmpty || userPassword.isEmpty)
{
//Display alert message
return;
}
答案 0 :(得分:0)
username是String可选。所以它可以是零。要解决此问题,您需要将其解包,如下面的代码段if ((userName?.isEmpty ||userPhoneNumber?.isEmpty || userPassword?.isEmpty))
有关详细信息,请查看此处:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html
答案 1 :(得分:0)
访问多个字段的惯用方法是:
if let userName = userNameTextField.text,
let userPhoneNumber = userPhoneNumberTextField.text,
let userPassword = userPasswordTextField.text,
let userReenterPassword = userReenterPasswordTextField.text {
// all values bound and not `nil`
// ...
} else {
// display alert message
return
}
或
func foo () {
guard let userName = userNameTextField.text,
let userPhoneNumber = userPhoneNumberTextField.text,
let userPassword = userPasswordTextField.text,
let userReenterPassword = userReenterPasswordTextField.text else {
// display alert message
return
}
// good here
// ...
}