簡體   English   中英

可選類型“字符串”的值? 檢查值是否為空時未展開

[英]value of optional type 'string?' not unwrapped when checking if values are empty

我正在使用SwiftxCode 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 ?? truenil ,則提供默認值。

userEmail?.isEmpty ?? true
  • lhs: Optional.Some(true) 。Some Optional.Some(true) -> true??左手邊不是nil ,請使用lhs值展開)
  • lhs: Optional.Some(false) 。Some Optional.Some(false) -> false??左側不是nil ,請使用lhs值展開)
  • lhs: Optional.None -> true??左側 nil ,因此使用右側的值)

您知道,當文本為nil ,您應該認為它為 ,因此為nil大小寫提供默認值true是適當的。

您需要為所有三個變量編寫類似的代碼,然后得到上面顯示的行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM