即使数值为零,Guard Let语句也不会触发

问题描述

这是我拥有的UIBarButtonItem:

@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
           }

IBAction下它下面的代码是无关紧要的,因为这是一个保护问题。即使我将字面值设置为nil,它也不会触发。在我的viewDidLoad中,输入:

    nameTextField.text = nil
    estimatedHeightTextField.text = nil
    descriptionTextView.text = nil

当我按下按钮时,在不更改这些文本的值的情况下,guard let语句仍然不会触发,并且下面的其余功能将执行。有什么想法吗?谢谢。

解决方法

如果仅检查文本字段是否为空,则可以执行以下操作:

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
    }

签出此答案:https://stackoverflow.com/a/24102758/12761873

,

UITextField文本属性的默认值为emptyString。即使您在检查其值之前将其分配为nil,它也永远不会返回nil。 BTW UIKeyInput协议具有一个专门用于此目的的名为hasText的属性。如果还希望避免用户仅输入空格和换行符,则可以在检查空格和换行之前对其进行修剪。您可以扩展UITextInput并实现自己的isEmpty属性。这将通过一个实现覆盖UITextFieldUITextView

extension UITextInput {
    var isEmpty: Bool {
        guard let textRange = self.textRange(from: beginningOfDocument,to: endOfDocument) else { return true }
        return text(in: textRange)?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == true
    }
}

let textField = UITextField()
textField.text = " \n "
textField.isEmpty   // true

let textView = UITextView()
textView.text = " \n a"
textView.isEmpty   // true