为什么即使我将该字段留空,我的UITextfField似乎也不为零?我的“其他"if语句的一部分未被读取 [英] Why does my UITextfField seems to be NOT nil, even if I leave the field empty? My "else" part of the if-statment is not being read

查看:39
本文介绍了为什么即使我将该字段留空,我的UITextfField似乎也不为零?我的“其他"if语句的一部分未被读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过制作包含客户数据的应用程序来练习快速编程.该应用程序具有多个文本字段,人们可以在其中输入他们的姓名,电子邮件地址,电话号码和购买的产品数量.然后使用提交"按钮将信息保存到数据库中.但是,如果其中一个字段为空,则应该引发错误,并且用户应该看到一条消息,让他/她知道其中一个字段为空.

I am practicing swift programing by making an app that holds customers' data. The app has several text fields where people are supposed to type their name, email address, phone number, and quantity of products purchased. Then with a 'submit' button they save that information into the data base. However, if one of the fields is empty, an error should be thrown and a message should appear to the user letting him/her know that one of the fields empty.

问题在于,即使文本字段为空,编译器也不会将其读取为nil,因此我的条件无法正常工作.

The problem is that even if the textfield is empty, the compiler is not reading it as nil, so my condition is not working.

为简单起见,我省略了很多代码.我将仅使用一个UITextField(客户名称),我的条件将检查TextField是否为空.如果为空,则应打印请输入有效名称".如果不是零,则应打印客户的姓名.

For simplicity, I am omitting a lot of code. I will only work with one UITextField (customer's name), and my condition will check if the TextField is empty or not. If empty, it should print "Please enter a valid name." if it is NOT nil, it should print the customer's name.

class RaffleViewControler: UIViewController, UITextFieldDelegate {


    @IBOutlet weak var customerNameTextField: UITextField!

    @IBAction func addCustomerName(_ sender: UITextField) {


    }


    @IBOutlet weak var submitButton: UIButton!


    @IBAction func submitCustomer(_ sender: UIButton) {

           if let name = customerNameTextField.text {
            print(name)

        } else {
            print("Please enter a valid name")
        }
}

或者,我也在用以下格式检查病情:

Alternatively, I was also checking my condition in the following format:

@IBAction func submitCustomer(_ sender: UIButton) {

               if customerNameTextField.text != nil {
                print("Congrats. Your data is in our database")

            } else {
                print("Please enter a valid name")
            }
  }

问题:

即使我将文本字段留空,编译器也不会读取条件的"else"部分.这似乎表明该字段永远不会为零.可能会发生什么?

Even if I leave the textfield empty, the compiler does not read the "else" part of the condition. Which seems to indicate that the field is never nil. What could be happening?

推荐答案

根据Apple

默认情况下,此字符串为@".

This string is @"" by default.

即默认情况下它不是nil.

I.e. it is not nil by default.

这篇关于为什么即使我将该字段留空,我的UITextfField似乎也不为零?我的“其他"if语句的一部分未被读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆