1

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?

sesc360
  • 3,155
  • 10
  • 44
  • 86

1 Answers1

0

userFirstName is optional, but you give it a value only when userFirstNameTextField.text is not nil, so you lose that Optional sense. In this case you should assign without checking if it is nil

userFirstName = userPasswordRepeatTextField.text

otherwise userFirstName should be just String

Sasha Kozachuk
  • 1,283
  • 3
  • 14
  • 21
  • maybe I am missing something... but when I would do this: `userFirstName = userFirstNameTextField.text` and the user puts in a name, it is still an unwrapped String, right? – sesc360 Mar 30 '16 at 12:50
  • So I thought I need to use optional binding to unwrap the value – sesc360 Mar 30 '16 at 12:51
  • @sesc360 please check out this answer http://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift – Sasha Kozachuk Mar 30 '16 at 12:52