【发布时间】: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的属性正是为此目的。