为什么我的 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

查看:36
本文介绍了为什么我的 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 是否为空.如果为空,则应打印请输入有效名称".如果它不是 nil,它应该打印客户的名字.

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?

推荐答案

根据苹果 文档:

这个字符串默认是@"".

This string is @"" by default.

即默认不为零.

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

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