Here is a UIBarButtonItem I have:
@IBAction func doneButtonPressed(_ sender: UIBarButtonItem) {
print("doneButton Pressed")
// Guard statement ensures that all fields have been satisfied, so that the JumpSpotAnnotation can be made, and no values are nil
guard let name = nameTextField.text,
let estimatedHeight = estimatedHeightTextField.text,
let locationDescription = descriptionTextView.text else {
nameRequiredLabel.isHidden = false
heightRequiredLabel.isHidden = false
descriptionRequiredLabel.isHidden = false
print("User did not put in all the required information.")
return
}
The code below it in the IBAction is irrelevant since this is a guard let problem. It won't trigger even when I literally set the values to nil. In my viewDidLoad I put:
nameTextField.text = nil
estimatedHeightTextField.text = nil
descriptionTextView.text = nil
And when I press the button, without changing the values of these texts, the guard let statement still doesn't trigger, and the rest of the function below executes. Any ideas why? Thanks.
If you are just checking that the text field is empty then you can do something like:
guard
let estimatedHeight = estimatedHeightTextField.text,
!estimatedHeight.isEmpty,
let locationDescription = descriptionTextView.text,
!locationDescription.isEmpty
else {
nameRequiredLabel.isHidden = false
heightRequiredLabel.isHidden = false
descriptionRequiredLabel.isHidden = false
print("User did not put in all the required information.")
return
}
Checkout out this answer: https://stackoverflow.com/a/24102758/12761873