【问题标题】:Guard Let statement not triggering even when values are nil即使值为 nil,Guard Let 语句也不会触发
【发布时间】:2020-12-07 20:32:23
【问题描述】:

这是我拥有的 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 语句仍然没有触发,下面的函数的其余部分将执行。任何想法为什么?谢谢。

【问题讨论】:

  • 单独调试和打印每个值?
  • 刚刚做了,它为所有三个打印了 Optional("") 。我很困惑,我认为守卫的全部意义在于它不能为零。我在做什么错/误解?
  • 如果它们打印Optional(""),它们是空的,而不是零。所以你应该测试第一个guard let name = nameTextField.text, !name.isEmpty else { ... }
  • @Larme 谢谢,这行得通。欣赏它
  • UITextField 文本属性默认值为空字符串。即使您在检查其值之前将 nil 分配给它,它也永远不会返回 nil。 BTW UIKeyInput 协议有一个名为hasText 的属性正是为此目的。

标签: ios swift xcode guard let


【解决方案1】:

UITextField 文本属性默认值为emptyString。它永远不会返回nil,即使你在检查它的值之前给它分配了 nil。顺便说一句,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

【讨论】:

    【解决方案2】:

    如果您只是检查文本字段是否为空,那么您可以执行以下操作:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      • 2017-02-26
      • 2023-04-07
      • 2015-09-19
      • 1970-01-01
      相关资源
      最近更新 更多