[英]How to check if NSDictionary is not nil in Swift 2
我在我的函數中將NSDictionary作為參數但是有問題因為不知道如何檢查該參數是否為nil。
我的功能看起來像這樣:
func doSmth(val : NSDictionary)
在我的函數內部,我試圖獲得一些值:
let action = val["action"] as! String
但是當接收參數val為nil時,得到錯誤“致命錯誤:在展開可選值時意外地發現nil”。
您還可以訪問allKeys
或allValues
屬性,並檢查數組是否包含如下所示的元素:
let dic = NSDictionary()
let total = dic.allKeys.count
if total > 0 {
// Something's in there
}
else {
// Nothing in there
}
編輯
以下是如何檢測NSDictionary是否為nil,如果它們是key,您是否正在尋找存在,以及它是否嘗試訪問它的值:
let yourKey = "yourKey"
if let dic = response.someDictionary as? NSDictionary {
// We've got a live one. NSDictionary is valid.
// Check the existence of key - OR check dic.allKeys.containsObject(yourKey).
let keyExists: Bool = false;
for var key as String in dic.allKeys {
if key == yourKey {
keyExists = true;
}
}
// If yourKey exists, access it's possible value.
if keyExists == true {
// Access your value
if let value = dic[yourKey] as? AnyObject {
// We're in business. We have the value!
}
else {
// yourKey does not contain a value.
}
}
else {
// yourKey does not exist in NSDictionary.
}
}
else {
// Call an ambulance. NSDictionary is nil.
}
該錯誤是由於假設(強制轉換)有時可能為零的值。 Swift非常棒,因為它允許在非常簡潔的語句中使用條件展開和條件轉換。 我推薦以下(適用於Swift 1-3):
使用“if let”有條件地檢查字典中的“action”。
用於? 有條件地將值轉換為String
if let actionString = val["action"] as? String {
// action is not nil, is a String type, and is now stored in actionString
} else {
// action was either nil, or not a String type
}
你的字典參數可能不是零。 問題可能是您的字典不包含鍵"action"
。
當你說val["action"]
,字典(作為NSDictionary
)返回一個Optional<AnyObject>
。 如果val
包含鍵"action"
,則返回Some(value)
。 如果val
不包含鍵"action"
,則返回None
,這與nil相同。
您可以在演員表中解包Optional
,並使用if-let
語句根據它是否為nil選擇一個操作過程:
if let action = val["action"] as? String {
// action is a String, not an Optional<String>
} else {
// The dictionary doesn't contain the key "action", and
// action isn't declared in this scope.
}
如果你真的認為val
本身可能是nil,你需要以這種方式聲明你的函數,並且你可以使用一個有點令人困惑的guard
語句重新打開val
來解包它:
func doSmth(val: NSDictionary?) {
guard let val = val else {
// If val vas passed in as nil, I get here.
return
}
// val is now an NSDictionary, not an Optional<NSDictionary>.
...
}
這與Swift 2並不特別相關。
如果字典可以為nil
則將其聲明為可選
func doSmth(val : NSDictionary?)
然后使用可選綁定進行檢查
if let valIsNonOptional = val {
let action = valIsNonOptional["action"] as! String
}
如果字典不是nil,代碼假定有一個包含String
值的鍵action
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.