Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if NSDictionary is not nil in Swift 2

Tags:

ios

swift

I'm getting NSDictionary as parameter in my function but having problem because don't know how to check if that parameter is not nil.

My function looks like this:

func doSmth(val : NSDictionary)

Inside my function I'm trying to get some values:

let action = val["action"] as! String

But getting error "fatal error: unexpectedly found nil while unwrapping an Optional value" when receive parameter val as nil.

like image 858
MantasG Avatar asked Aug 19 '15 21:08

MantasG


2 Answers

The error is due to assuming (force casting) a value that can sometimes be nil. Swift is awesome, because it allows conditional unwraps and conditional casts in very concise statements. I recommend the following (for Swift 1-3):

Use "if let" to conditionally check for "action" in the dictionary.

Use as? to conditionally cast the value to a 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
}
like image 181
Lytic Avatar answered Oct 19 '22 03:10

Lytic


You can also access the allKeys or alternatively allValues property and check if the array contains any elements like so:

let dic = NSDictionary()
let total = dic.allKeys.count

    if total > 0 {

        // Something's in there

    }

    else {

        // Nothing in there
    }

EDIT

Here is how you can detect if the NSDictionary is nil, if they key you are looking for exists, and if it does attempt to access it's value:

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.
}
like image 33
Brandon A Avatar answered Oct 19 '22 02:10

Brandon A