2016-02-22 23 views
0

我似乎無法在其他問題上找到解決方案。Swift Locksmith:致命錯誤:意外地發現零,同時展開一個可選值

我正在使用Swift Locksmith(https://github.com/matthewpalmer/Locksmith)庫。

以下是我有:

let dictionary = Locksmith.loadDataForUserAccount("AppData") 

當我打印出來的字典,我得到:

Optional(["username": test, "password": test123]) 

然而,當我嘗試分配這些值變量傳遞長我似乎他一個事故和出現錯誤:

fatal error: unexpectedly found nil while unwrapping an Optional value

我試圖賦予它像這樣:

username = dictionary["username"] 

哪位告訴我:

Type '[String : AnyObject]?' has no subscript members

我試圖用.stringValue像這樣:

dictionary["username"].stringValue 

的Xcode然後叫我「修復它」,所以我點擊修復按鈕然後xcode給了我這個:

username = dictionary!["username"]!.stringValue 

tl; dr所以,我的問題

如何從字典(鑰匙串項目)中獲取用戶名和密碼並將其分配給變量,以便我可以將它們傳遞給新視圖?

回答

-1

您的字典是可選的。 讓你可以這樣做

let username = dictionary!["username"] 

用戶名
let userNameString = dictionary!["username"] as! String 
+0

同樣的錯誤:致命錯誤:意外地發現零,同時展開一個可選值 – JamesG

1

主要涉及兩個自選:字典本身(由loadDataForUserAccount返回),每個標結果(如["username"]["password"])。當您處理很多選項時,我建議完全避免使用!運營商。你應該只使用,當你當然結果將從來沒有nil。而且,由於您正在處理鑰匙串,因此無法保證。

相反,您應該使用if letguard let打開您需要的每個對象,並且只有在得到您要查找的結果時才繼續。下面是使用guard let一個例子,這是我想你可能想:

func authenticate() { 
    guard let dictionary = Locksmith.loadDataForUserAccount("AppData"), 
      let username = dictionary["username"], 
      let password = dictionary["password"] else { 
      // nothing stored in keychain, the user is not authenticated 
      return 
    } 

    print("username is \(username).") 
    print("passsword is \(password).") 
} 

您也可以使用if let改寫這個:

func authenticate() { 
    if let dictionary = Locksmith.loadDataForUserAccount("AppData"), 
     let username = dictionary["username"], 
     let password = dictionary["password"] { 
     print("username is \(username).") 
     print("password is \(password).") 
    } else { 
     // nothing stored in keychain, the user is not authenticated 
    } 
} 

我喜歡guard let在這種情況下,因爲它更清楚地表達了到閱讀你的代碼什麼是最佳/理想的代碼路徑。

相關問題