David Seek David Seek - 1 month ago 7
Swift Question

How to create a switch expression with UITextFields in Swift 3

I want to check my

UITextFields
for their
.text
status. Execute a function on
!= ""
and show an alert view
if == ""
. Since I have 5 different
UITextFields
I thought of a
switch
statement.

@IBAction func doneButton(_ sender: Any) {

let indexPath = IndexPath(row: 0, section: 0)
let cell = self.tableView.cellForRow(at: indexPath) as! SetupCell

var textFields: [UITextField] = []

textFields = [cell.nameTF,
cell.townTF,
cell.birthdayTF,
cell.genreTF,
cell.deejayTF]

for tf in textFields {

print("called") // is printed

if tf.text != "" {

print("not empty") // is printed

switch UITextField() {
case cell.nameTF:
saveCredential(ME, "name", cell.nameTF.text!)
case cell.birthdayTF:
saveCredential(ME, "birthday", cell.birthdayTF.text!)
case cell.townTF:
saveCredential(ME, "town", cell.townTF.text!)
case cell.deejayTF:
saveCredential(ME, "deejayName", cell.deejayTF.text!)
case cell.genreTF:
saveCredential(ME, "genre", cell.genreTF.text!)
default:
break
}
} else {

print("is empty") // printed

switch UITextField() {
case cell.nameTF:
presentAlertView(self, title: "Error", message: "Name missing")
case cell.birthdayTF:
presentAlertView(self, title: "Error", message: "Birthday missing")
case cell.townTF:
presentAlertView(self, title: "Error", message: "Town missing")
case cell.deejayTF:
presentAlertView(self, title: "Error", message: "Deejay name missing")
case cell.genreTF:
presentAlertView(self, title: "Error", message: "Genre missing")
default:
break
}
}
}
}


But the code within the
switch
statement is not executed. Neither the case if empty, nor if not. I believe the problem may be in
switch UITextField()
, but I can't figure out a solution. What am I missing? Help is very appreciated.

PS. The
saveCredential
as well as the
presentAlertView
are perfectly working on other parts of the App, so that might not be the issue. But to be sure:

func presentAlertView(_ vc: UIViewController, title: String, message: String?) {
var alert = UIAlertController(title: title, message: nil, preferredStyle: UIAlertControllerStyle.alert)
if message != nil {
alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
}
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
vc.present(alert, animated: true, completion: nil)
}

Answer

The problem is you are passing the new instance of UITextFiled with switch statements instead of passing object from Array.

switch tf {

Instead of

switch UITextField() {