if / else语句总是要去别的吗?

时间:2016-11-20 21:31:19

标签: swift

基本上,我想要做的就是获取文本字段数据,将其放入数组然后检查用户名/密码是否大于或等于6.我完全迷失了为什么这总是去别的?答案可能很明显,但我被困住了!

代码:

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()
}

1 个答案:

答案 0 :(得分:2)

正如@Martin R指出的那样,你的两个数组都由一个元素组成,因此.count在这种情况下返回1。

由于您正在尝试检查密码和用户名长度是否为>= 6,因此根本不需要数组。只需这样做

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
}