mardi 26 novembre 2019

Best way to save TextField inputs if conditions are met in Swift

I have a form with 2 textFields: link A and link B. If empty, I save a custom string (ie: "no link A"), and if filled, it needs to be valid, otherwise I show an alert. For checking the validity of the url I use this

Is there a cleaner way to do this rather than using so many 'if' statements?

linkA = linkATextField.text      
linkB = linkBTextField.text

     @IBAction func doneButton(_ sender: Any) {

            if linkA.isEmpty && linkB.isEmpty {
                linkA = "no link A"
                linkB = "no link B"
                saveData()
            } else {
                if linkA.isEmpty == false && linkB.isEmpty == false  {
                    if linkA.isValidURL && linkB.isValidURL {
                         saveData()
                    } else {
                        showErrorAlert()
                    }
                }
                if linkA.isEmpty && linkB.isEmpty == false {
                    linkA = "no link A"
                    if linkB.isValidURL {
                         saveData()
                    } else {
                        showErrorAlert()
                    }
                }
                if linkA.isEmpty == false && linkB.isEmpty {
                    linkB = "no link B"
                    if linkA.isValidURL {
                         saveData()
                    } else {
                        showErrorAlert()
                    }
                }
            }

        }

Aucun commentaire:

Enregistrer un commentaire