I am still trying to wrap my head around optionals in practice. I have a user form created where some textFields can be not filled out (first or last name of the user).
My thought is, it should be processed like this:
@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
}
}
But it tells me, that userFirstName and userLastName are never used. My questions are:
Why is it not used if I assign them using the optional binding? And is this the right way to parse textfield data or how could I streamline this code?