我正在尝试制作所有必需的文本字段,以确保用户不会将其留空。我试过这个,但由于某种原因,它没有用。我觉得我的逻辑是正确的,但这是一个快速逻辑的问题
这是我的代码:
let title = txtTitle.text!
let location = txtWhere.text!
let when = txtWhen.text!
if title != nil && location != nil && when != nil {
var titleArray = [String]()
var whereArray = [String]()
var whenArray = [String]()
let titleObject = UserDefaults.standard.object(forKey: "saveTitle")
let whereObject = UserDefaults.standard.object(forKey: "saveLocation")
let whenObject = UserDefaults.standard.object(forKey: "saveWhen")
if let tempTitle = titleObject as? [String] {
titleArray = tempTitle
titleArray.append(txtTitle.text!)
print(titleArray)
}
else {
titleArray = [txtTitle.text!]
}
if let tempWhere = whereObject as? [String] {
whereArray = tempWhere
whereArray.append(txtWhere.text!)
//print(titleArray)
}
else {
whereArray = [txtWhere.text!]
}
if let tempWhen = whenObject as? [String] {
whenArray = tempWhen
whenArray.append(txtWhen.text!)
//print(titleArray)
}
else {
whenArray = [txtWhen.text!]
}
UserDefaults.standard.set(titleArray, forKey: "saveTitle")
UserDefaults.standard.set(whereArray, forKey: "saveLocation")
UserDefaults.standard.set(whenArray, forKey: "saveWhen")
txtTitle.text = ""
txtWhere.text = ""
txtWhen.text = ""
txtTime.text = ""
}
else
{
errMsg.isHidden = false
errMsg.text = "All fields are required"
}
}
答案 0 :(得分:5)
要可靠地检查文本字段的text
属性是否不是nil
而不是空的,请使用
if let title = txtTitle.text, !title.isEmpty,
let location = txtWhere.text, !location.isEmpty,
let when = txtWhen.text, !when.isEmpty { ...
如果所有条件都通过,则可以安全地解开三个变量。
答案 1 :(得分:1)
一个。您不应强制解包(FILES.append("name.txt")
):而是检查可选值
湾您可能想要检查空字符串,而不仅仅是txtTitle.text!
那就是说,你可以测试这样的有效性:
nil
或者更好(谢谢Leo Dabus):
let title = txtTitle.text
if title?.isEmpty == false {
...// title was filled
}
答案 2 :(得分:1)
TEXTFIELD验证 ======================>
$cookiesRaw = $conn->httpRequest->getHeader('Cookie');
if(count($cookiesRaw)) {
$cookiesArr = \GuzzleHttp\Psr7\parse_header($cookiesRaw)[0]; // Array of cookies
}