可选类型'字符串的值?'未解开的错误

时间:2015-10-18 03:48:31

标签: ios swift

第一次在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;
    }

2 个答案:

答案 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
  // ...
}