Why does my UITextfField seems to be NOT nil, even if I leave the field empty? My quot;elsequot; part of the if-statment is not being read(为什么我的 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 语句未被读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我的 UITextfField 似乎不为零,即使我将字段留空?我的“其他"部分 if 语句未被读取
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01