[英]Non-optional expression of type uitextfield used in a check for optionals
我正在做一個UIAlertController,並收到以下消息:“用於檢查可選項的uitextfield類型的非可選表達式”。 這是我擁有“如果讓我的領域”的行。
我得到以下代碼:
let alertController = UIAlertController(title: "Adding", message: "Type something", preferredStyle: UIAlertControllerStyle.alert)
let DestructiveAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
if let field : UITextField = (alertController.textFields? [0])! as UITextField {
if field.text != "" {
//my actions
}
}
let okAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
}
alertController.addTextField { (textField) in
textField.placeholder = "Type designation here"
}
alertController.addAction(okAction)
alertController.addAction(DestructiveAction)
self.present(alertController, animated: true, completion: nil)
}
誰能告訴我如何刪除此警告? 我試圖刪除“!” 沒有成功。
您必須解開該值,因此它是非可選的。 這就是該消息告訴您的內容。
由於您確實已將文本字段添加到了警報控制器,因此您無需進行任何檢查,並且可以縮短代碼:
let field = alertController.textFields![0] // or textFields.first!
沒有類型注釋,沒有類型轉換,編譯器可以推斷類型。
要檢查空字符串,還有一種更方便的語法:
if !field.text.isEmpty { ...
您無需進行alertController.textFields
, alertController.textFields
的類型已經是[UITextField]
。 真正導致問題的原因是添加演員表。
let alertController = UIAlertController(title: "Adding", message: "Type something", preferredStyle: UIAlertControllerStyle.alert)
let DestructiveAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
if let field : UITextField = alertController.textFields?[0] {
if field.text != "" {
//my actions
}
}
}
我想向您展示更多。 您不需要設置類型,我會嘗試使條件盡可能具體。
let alertController = UIAlertController(title: "Adding", message: "Type something", preferredStyle: UIAlertControllerStyle.alert)
let DestructiveAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
if let text = alertController.textFields?[0].text, !text.isEmpty {
//my actions
}
}
另外,我想我會在這里使用警衛。
let alertController = UIAlertController(title: "Adding", message: "Type something", preferredStyle: UIAlertControllerStyle.alert)
let DestructiveAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
guard let text = alertController.textFields?[0].text, !text.isEmpty else {
return
}
//my actions
}
在做(alertController.textFields? [0])! as UITextField
(alertController.textFields? [0])! as UITextField
,實際上沒有任何意義,因為這意味着您正在嘗試將alertController.textFields[0]
轉換為UITextField
時,它已經是一種UITextField
。
相反,您應該做的是檢查alertController.textFields
的第一個元素alertController.textFields
存在,您可以使用下面的代碼來做到這一點。
if let field : UITextField = alertController.textFields.first {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.