[英]value of optional type 'string?' not unwrapped when checking if values are empty
我正在使用Swift在xCode 7內構建一個非常簡單的登錄驗證應用程序 。 我對Swift和構建應用程序來說是非常陌生的 ,所以我在部分代碼上遇到了一些困難。
我正在檢查用戶是否將任何字段留空,如果有,他們將收到錯誤警報消息。
但是,當我去構建項目時,出現錯誤:
可選類型'String?'的值 不展開
這是我的代碼:
let userEmail = userEmailTextField.text
let userPassword = userPasswordTextField.text
let userRepeatPassword = repeatPasswordTextField.text
if(userEmail.isEmpty || userPassword.isEmpty || userRepeatPassword.isEmpty){
displayAlertMessage("All fields are required.") // custom made function
return;
}
任何幫助表示贊賞。
另外,如果有人可以解釋為什么我的代碼無法正常運行,那真是太棒了! 因為,我似乎無法理解其他論壇的解釋或修正。
這里的問題是UITextField
的屬性text
是一個optionl字符串,因此您必須像這樣進行更改:
let userEmail = userEmailTextField.text!
let userPassword = userPasswordTextField.text!
let userRepeatPassword = repeatPasswordTextField.text!
或像這樣使用
guard let userEmail = userEmail, let userPassword = userPassword, let userRepeatPassword = userRepeatPassword where !userEmail.isEmpty && !userPassword.isEmpty && !userRepeatPassword.isEmpty else {
displayAlertMessage("All fields are required.") // custom made function
return;
}
如前所述, UITextField
的屬性text
的類型為String?
(又名Optional<String>
),因此您不能直接應用方法或獲取String
屬性。
強制展開( !
)會非常危險,因為該屬性實際上可能nil
。
在這種情況下,您可以使用一些選項來處理Optional值:
if let
,但是guard let
或有時while let
有用。 ?.
表示?.
。 也許您正在其他地方使用它。 ??
。 對於后兩個,我得到以下一行:
if((userEmail?.isEmpty ?? true) || (userPassword?.isEmpty ?? true) || (userRepeatPassword?.isEmpty ?? true)) {
如您所見, userEmail
的類型是String?
,因此我選擇了可選鏈接:
userEmail?.isEmpty
可能返回三種值:
Optional.Some(true)
Optional.Some(false)
Optional.None
(這稱為nil
) (為了便於閱讀,我省略了指定<Bool>
。)
它仍然是可選的,所以我添加了?? true
?? true
為nil
,則提供默認值。
userEmail?.isEmpty ?? true
Optional.Some(true)
。Some Optional.Some(true)
-> true
( ??
左手邊不是nil
,請使用lhs值展開) Optional.Some(false)
。Some Optional.Some(false)
-> false
( ??
左側不是nil
,請使用lhs值展開) Optional.None
-> true
( ??
左側為 nil
,因此使用右側的值) 您知道,當文本為nil
,您應該認為它為空 ,因此為nil
大小寫提供默認值true
是適當的。
您需要為所有三個變量編寫類似的代碼,然后得到上面顯示的行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.