Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/111.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 可选类型“字符串”的值未展开错误_Ios_Swift - Fatal编程技术网

Ios 可选类型“字符串”的值未展开错误

Ios 可选类型“字符串”的值未展开错误,ios,swift,Ios,Swift,第一次用Swift编码。我在为if语句声明条件的行上不断得到一个可选类型为“String?”而不是“unwrapped”的值。我做错了什么 @IBAction func registerButtonTapped(sender: AnyObject) { let userName = userNameTextField.text; let userPhoneNumber = userPhoneNumberTextField.text); let userPassword

第一次用Swift编码。我在为if语句声明条件的行上不断得到一个可选类型为“String?”而不是“unwrapped”的值。我做错了什么

@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;
    }

用户名是可选的字符串。所以它可以是零。为了解决这个问题,您需要像下面的代码片段一样打开它,如果userName?.isEmpty | | userPhoneNumber?.isEmpty | | userPassword?.isEmpty 有关更多信息,请查看此处:
访问多个字段的惯用方法是:

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
}


你不需要像这样打开它吗:userName!。isEmpty | | |…?苹果正在推动开发人员永远不要只使用可选选项!而且,它们对API应用相同的规则才有意义。这是因为它可以是nil,如果用声明它没有任何区别?或用于运行代码。使用!实际上只是删除了Xcode中的警告,这非常方便,尤其是在涉及API代码时。如果你没有意识到这实际上是一个选择,你只是自找麻烦。
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
  // ...
}