我仍然试图在实践中绕过选项。 我创建了一个用户表单,其中某些textFields可能未填写(用户的名字或姓氏)。
我的想法是,它应该像这样处理:
@IBAction func signUpButtonTapped(sender: AnyObject) {
// Get information from register form
let userEmail: String
let userPassword: String
let userPasswordRepeat: String
let userFirstName: String?
let userLastName: String?
guard let email = userEmailAddressTextField.text,
let password = userPasswordTextField.text,
let passwordRepeat = userPasswordRepeatTextField.text else {
return
}
userEmail = email
userPassword = password
userPasswordRepeat = passwordRepeat
if let firstName = userFirstNameTextField.text, let lastName = userEmailAddressTextField.text {
userFirstName = firstName
userLastName = lastName
}
// Check if password is the same when registering
if (userPassword != userPasswordRepeat) {
displayAlertViewController(title: "Alert", message: "Passwords do not match")
return
}
// If email, password, first name or last name is missing display alert
if(userEmail.isEmpty || userPassword.isEmpty) {
displayAlertViewController(title: "Alert", message: "All fields need to be filled in.")
return
}
}
但它告诉我,从不使用userFirstName和userLastName。我的问题是:
如果我使用可选绑定分配它们,为什么不使用它?这是解析文本字段数据的正确方法,或者我如何简化此代码?
答案 0 :(得分:0)
userFirstName是可选的,但是只有当userFirstNameTextField.text不为nil时才给它一个值,所以你会失去那个Optional sense。 在这种情况下,您应该在不检查它是否为零的情况下进行分配
userFirstName = userPasswordRepeatTextField.text
否则userFirstName应该只是String