I am trying to make all of my text fields required to make sure that users does not leave it empty. I tried this but for some reason it's not working. I feel like my logic is correct, but it's an issue with swift's logic
Here is my code:
let title = txtTitle.text!
let location = txtWhere.text!
let when = txtWhen.text!
if title != nil && location != nil && when != nil {
var titleArray = [String]()
var whereArray = [String]()
var whenArray = [String]()
let titleObject = UserDefaults.standard.object(forKey: "saveTitle")
let whereObject = UserDefaults.standard.object(forKey: "saveLocation")
let whenObject = UserDefaults.standard.object(forKey: "saveWhen")
if let tempTitle = titleObject as? [String] {
titleArray = tempTitle
titleArray.append(txtTitle.text!)
print(titleArray)
}
else {
titleArray = [txtTitle.text!]
}
if let tempWhere = whereObject as? [String] {
whereArray = tempWhere
whereArray.append(txtWhere.text!)
//print(titleArray)
}
else {
whereArray = [txtWhere.text!]
}
if let tempWhen = whenObject as? [String] {
whenArray = tempWhen
whenArray.append(txtWhen.text!)
//print(titleArray)
}
else {
whenArray = [txtWhen.text!]
}
UserDefaults.standard.set(titleArray, forKey: "saveTitle")
UserDefaults.standard.set(whereArray, forKey: "saveLocation")
UserDefaults.standard.set(whenArray, forKey: "saveWhen")
txtTitle.text = ""
txtWhere.text = ""
txtWhen.text = ""
txtTime.text = ""
}
else
{
errMsg.isHidden = false
errMsg.text = "All fields are required"
}
}
To check reliably if the
text
properties of the text fields are notnil
and not empty useIf all conditions are passed the three variables are safely unwrapped.
TEXTFIELD VALIDATION ======================>
a. You shouldn't force unwrap (
txtTitle.text!
): instead check the optional valueb. You may want to check for empty strings instead of just for
nil
That said, you can test for validity like that:
Or better (thank you Leo Dabus):