用于条件绑定的Swift Initializer必须具有Optional类型,如果使用if let语句,则不能为'Bool'错误

时间:2019-02-24 15:48:51

标签: swift

所以我正在用Xcode编写应用程序,这是代码的一部分:

func Signup(_ sender: Any) {
        if let email = Email.text != nil, let password = 

第二行出现错误

  

用于条件绑定的初始化程序必须具有可选类型,而不是'Bool'

你能帮我吗?

1 个答案:

答案 0 :(得分:1)

很显然,您应该删除该(gdb) p b._vptr$base[0] $77 = (int (*)(void)) 0x100006ee0 <base::basefunc()> (gdb) p b._vptr$base[1] $78 = (int (*)(void)) 0x100006b30 <base::~base()> (gdb) p b._vptr$base[2] $79 = (int (*)(void)) 0x100006f10 <base::~base()> (gdb) p b._vptr$base[3] $80 = (int (*)(void)) 0x7fff87fd7fe8 (gdb) p b._vptr$base[4] $81 = (int (*)(void)) 0x10000eda8 <typeinfo name for base> (gdb) p b._vptr$base[5] $82 = (int (*)(void)) 0x0 (gdb) p d._vptr$base[0] $88 = (int (*)(void)) 0x100006fb0 <derived::basefunc()> (gdb) p d._vptr$base[1] $89 = (int (*)(void)) 0x100006b00 <derived::~derived()> (gdb) p d._vptr$base[2] $90 = (int (*)(void)) 0x100006fe0 <derived::~derived()> (gdb) p d._vptr$base[3] $91 = (int (*)(void)) 0x7fff87fd8058 (gdb) p d._vptr$base[4] $92 = (int (*)(void)) 0x10000edae <typeinfo name for derived> (gdb) p d._vptr$base[5] $93 = (int (*)(void)) 0x10000f248 <typeinfo for base> (gdb) p d._vptr$base[6] $94 = (int (*)(void)) 0x0

我还建议:

  • 修剪空白,以便有人不会进入空间以通过验证;
  • 使用修剪后的字符串中的!= nil确保其中存在某些内容;
  • 以小写字母开头的属性和方法名称;
  • 我亲自为我的isEmpty属性提供了一个后缀UITextField(因此,我可以将TextField文本字段与emailTextField字符串区分开来。

因此,也许像这样:

email

例如,您可能要检查电子邮件和密码是否通过了一些基本规则:

@IBAction func didTapSignup(_ sender: Any) {
    guard let email = emailTextField.text?.trimmingCharacters(in: .whitespaces),
        !email.isEmpty,
        let password = passwordTextField.text?.trimmingCharacters(in: .whitespaces),
        !password.isEmpty else {
            // tell the user that validation failed here ...

            // ... and then return
            return
    }

    // do something with `email` and `password`
}

然后

let emailRegexString = "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"  // oversimplified email regex

func isAcceptable(email: String, password: String) -> Bool {
    let isEmailAcceptable = email.range(of: emailRegexString, options: .regularExpression) != nil
    let isPasswordAcceptable = password.count > 4

    return isEmailAcceptable && isPasswordAcceptable
}

请注意,正则表达式主要是over-simplified email validation。但是,如果您确实需要,可以go nuts on the regex


我还至少要设置我的电子邮件和密码文本字段,以便不允许使用空格。因此,为电子邮件和密码文本字段指定@IBAction func didTapSignup(_ sender: Any) { guard let email = emailTextField.text?.trimmingCharacters(in: .whitespaces), let password = passwordTextField.text?.trimmingCharacters(in: .whitespaces), isAcceptable(email: email, password: password) else { // tell the user that validation failed here ... // ... and then return return } // do something with `email` and `password` } ,然后禁止空格:

delegate