Polo Polo - 14 days ago 6
Swift Question

if/else statement always going to else?

Basically, all I want to do is get the textfields data, put it into an array and then check to see if the username/password is greater than or equal to 6. I'm completely lost as to why this is always going to else? The answer is probably obvious, but I'm stuck!
Code:

import UIKit

class SignUpVC: UIViewController {

//MARK: Outlets
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var showErrorLabel: UILabel!

//MARK: Actions
@IBAction func goBackToLoginButton(_ sender: Any) {

let username: String = usernameTextField.text!
let password: String = passwordTextField.text!

//username/password content into an array
let userNameArray = ["\(username)"]
let passwordArray = ["\(password)"]

//Checks to see if username & password is greater than or equal to 6
if userNameArray.count >= 6 && passwordArray.count >= 6 {
print("Username and password is greater than or equal to 6!")
} else {
print("Username and password is less than 6!")
showErrorLabel.isHidden = false
}

//Dismiss old views
dismiss(animated: true, completion: nil)
}

override func viewDidLoad() {
super.viewDidLoad()
}

Answer

As what @Martin R pointed out, both of your arrays consist of a single element hence .count returns 1 for this case.

Since you're trying to check to see if the password and username lengths are >= 6, then there's no need for the arrays at all. Just do this instead

let userName: String = usernameTextField.text!
let password: String = passwordTextField.text!

if userName.characters.count >= 6 && password.characters.count >= 6
{
  print("Username and password is greater than or equal to 6!")
}
else
{
   print("Username or password is less than 6!")
   showErrorLabel.isHidden = false
}
Comments