0

Coding in Swift for the first time. I keep getting a "Value of optional type 'String?' not unwrapped" error on the line where I declare the condition for the if statement. What am I doing wrong?

@IBAction func registerButtonTapped(sender: AnyObject) {

    let userName = userNameTextField.text;
    let userPhoneNumber = userPhoneNumberTextField.text);
    let userPassword = userPasswordTextField.text;
    let userReenterPassword = userReenterPasswordTextField.text;

    // Check for empty fields
    if(userName.isEmpty || userPhoneNumber.isEmpty || userPassword.isEmpty)
    {
        //Display alert message

        return;
    }

2 Answers2

0

username is a String optional. So it can be nil. In order to solve the issue you need to unwrap it like in the following code snippet if ((userName?.isEmpty ||userPhoneNumber?.isEmpty || userPassword?.isEmpty)) For more info take a look here: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

Access Denied
  • 8,723
  • 4
  • 42
  • 72
  • Wouldn't you need to unwrap it like so: `userName!.isEmpty || ...`? – adamsuskin Oct 18 '15 at 03:55
  • Apple is pushing devs to never just use optional! and it only makes sense that they apply the same rules to the API's. The reason for this is that it can be nil, and it doesn't make any difference if it is declared with ? or ! for running the code. Using ! actually just removes the warnings in Xcode which are really handy, especially when it comes to API code. If you don't realize it actually is an optional you are just asking for trouble. http://stackoverflow.com/questions/32621022/why-was-uitextfields-text-property-changed-to-an-optional-in-swift-2 – Access Denied Oct 18 '15 at 04:08
0

The idiomatic approach to accessing multiple fields is:

if let userName = userNameTextField.text,
    let userPhoneNumber = userPhoneNumberTextField.text,
    let userPassword = userPasswordTextField.text,
    let userReenterPassword = userReenterPasswordTextField.text {
  // all values bound and not `nil`
  // ...
} else {
  // display alert message

  return
}

or

func foo () {
  guard let userName = userNameTextField.text,
        let userPhoneNumber = userPhoneNumberTextField.text,
        let userPassword = userPasswordTextField.text,
        let userReenterPassword = userReenterPasswordTextField.text else {
     // display alert message

     return
    }

  // good here
  // ...
}
GoZoner
  • 67,920
  • 20
  • 95
  • 145