可选类型'Bool'不能用作布尔值; 而是测试'!= nil'

Gha*_*aei 6 optional swift

可选类型'Bool'不能用作布尔值; 而是测试'!= nil'

在此输入图像描述

如果通过替换if条件(after),第二个if条件从未运行,我首先得到一个错误.任何的想法?

之前:

if(userEmail?.isEmpty || userPassword?.isEmpty || userRepeatPassword?.isEmpty){
      displayMyAlertMessage("All fields are required")
      return
}

if(userPassword != userRepeatPassword){
      displayMyAlertMessage("Passwords do not match.")
}
Run Code Online (Sandbox Code Playgroud)

后:

if(userEmail != nil || userPassword != nil || userRepeatPassword != nil){
      displayMyAlertMessage("All fields are required")
      return
}

if(userPassword != userRepeatPassword){
      displayMyAlertMessage("Passwords do not match.")
}
Run Code Online (Sandbox Code Playgroud)

小智 5

你需要用!而不是包裹它?。
这将解决错误消息:

if (username!.isEmpty) .....
Run Code Online (Sandbox Code Playgroud)


Edu*_*ard 5

if(userEmail!.isEmpty || userPassword!.isEmpty || userRepeatPassword!.isEmpty)
Run Code Online (Sandbox Code Playgroud)

您无法检查可选值,因为您可能已经知道,作为可选值意味着它可以存在或不存在。调用了一种解决方案force unwrapping,它是通过使用“!”来完成的。( 感叹号 )。“?” (问号)只是让编译器知道可能有或可能没有值,因此使用“!” 我们告诉编译器我们知道它可能是也可能不是该变量内的值,但我们知道将会有一个值,即使它是一个 EMPTY STRING,这与其他考虑空字符串或空数组(如“false”)的编程语言不同。斯威夫特的情况并非如此。

条件语句中的表达式必须是有效的布尔结果。


Ica*_*aro 3

您正在检查该值是否与 nil 不同,如果不同则返回,根据您的评论和您的第二个评论(如果您可能想检查它是否为零)。

println("Checking login details")
if(userEmail.isEmpty || userPassword.isEmpty || userRepeatPassword.isEmpty){
      displayMyAlertMessage("All fields are required")
      println("Fail to login not all fields where fill") 
      return
} else if(userPassword != userRepeatPassword){
      displayMyAlertMessage("Passwords do not match.")
      println("Fail to login password does not match") 
} else {  
  var uiAlert = UIAlertController(title: "Alert", message: "Registration was successful", preferredStyle: UIAlertControllerStyle.Alert)
  self.presentViewController(uiAlert, animated: true, completion: nil)
  uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
   dismissViewControllerAnimated(true, completion:nil)
  }))
}
Run Code Online (Sandbox Code Playgroud)