我在使用guard let 时遇到 fatal error 。错误如下:
Initializer for conditional binding must have Optional type not 'String'
下面是我使用过的代码:
@IBAction func signUpButtonPressed(sender: UIButton) {
guard let email = emailTextField.text! where emailTextField.text!.characters.count > 0 else {
// alert
return
}
guard let password = passwordTextField.text! where passwordTextField.text!.characters.count > 0 else {
// alert
return
}
self.registerUserAsync(email, password: password)
}
最佳答案
您应该非常小心选择选项。使用 !
你告诉 Swift 编译器你可以保证该值存在。
尝试这样做:
@IBAction func signUpButtonPressed(sender: UIButton) {
guard let email = emailTextField.text where email.characters.count > 0 else {
// alert
return
}
guard let password = passwordTextField.text where password.characters.count > 0 else {
// alert
return
}
self.registerUserAsync(email, password: password)
Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”.
有关选项的更多信息,您可以在此处找到 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309
关于swift - 守卫让错误: Initializer for conditional binding must have Optional type not 'String' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37858071/