Checking for required text fields for login

2018-06-05 08:31:45

I wrote this script and it's working quite well however I think there's too much if else statements on it. How could I change them for a switch statement?

@IBAction func sendLoginParameters(_ sender: UIButton) {

if correoTextField.text?.isEmpty == true && contrasenaTextField.text?.isEmpty == true {

let alertMessage = UIAlertController(title: "Datos requeridos", message: "Favor de llenar todos los datos requeridos (CORREO Y CONTRASEÑA) antes de continuar", preferredStyle: .alert)

alertMessage.addAction(UIAlertAction(title: "Aceptar", style: .default, handler: nil))

self.present(alertMessage, animated: true, completion: nil)

return

} else if correoTextField.text?.isEmpty == true {

let alertMessage = UIAlertController(title: "Datos requeridos", message: "Favor de llenar todos los datos requeridos (CORREO) antes de continuar", preferredStyle: .alert)

alertMessage.addAction(UIAlertAction(title: "Aceptar", style: .def

  • In my opinion the issue here is not the repetition of if else but the repetition of similar alert message code.

    For example, you could continue using if else but without these repetitions:

    guard let correoText = correoTextField.text, let contrasenaText = contrasenaTextField.text else {

    fatalError("The outlets are not properly connected")

    }

    var msg: String? = nil

    if correoText.isEmpty && contrasenaText.isEmpty {

    msg = "CORREO Y CONTRASEÑA"

    } else if correoText.isEmpty {

    msg = "CORREO"

    } else if contrasenaText.isEmpty {

    msg = "CONTRASEÑA"

    }

    if let msg = msg {

    let alertMessage = UIAlertController(title: "Datos requeridos", message: "Favor de llenar todos los datos requeridos (\(msg)) antes de continuar", preferredStyle: .alert)

    alertMessage.addAction(UIAlertAction(title: "Aceptar", style: .default, handler: nil))

    self.present(alertMessage, animated: true, completion: nil)

    }

    But if you want to use switch, you can switch on a tuple representing the two bool

    2018-06-05 09:41:41
  • A better solution may be to just disable the login button until all fields are filled.

    However if you want to stick to this alert the error approach then move this logic out of the VC and into your login/api class.

    Now the VC doesn't need to check the inputs at all, it just sends what it has to the login class and if any error occurs then it presents the alert with the error message.

    More on how to do that here: https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html

    2018-06-05 10:52:57