Search code examples
swiftclosuresalamofire

Swift: Cannot subscript a value of type 'Dictionary<String, NSObject>?'


EDIT: Not a DUPLICATE:

That solution gives 'Could not find an overload for 'subscript' that accepts the supplied arguments' error. So, no this is NOT a duplicate.

Here is the function declaration.

        func auth(user: String, pass: String, completion: (returned: Bool, error: Bool, response: Dictionary<String, NSObject>?) -> ()){

response can be nil }

Now I'm trying to access value passed back in another file and getting an error:

        if let labelString = response["error_description"] as! String?{
            self.labelPrompt.text = labelString
        }

Error: Cannot subscript a value of type 'Dictionary?' with an index of type 'String'

enter image description here


Solution

  • It is a duplicate of the linked question: what you need is to unwrap the dictionary before using it with a subscript.

    There's many ways ("if let", etc) and the linked answer gives the solution of using "optional binding" by adding a ? between the variable holding the dictionary and the subscript.

    Example in a Playground:

    var response: Dictionary<String, NSObject>? = nil
    
    // NOTICE THE "?" BETWEEN THE VARIABLE AND THE SUBSCRIPT
    
    if let labelString = response?["error_description"] as? String {
        println(labelString)  // not executed because value for key is nil
    }
    
    response = ["test":"yep"]
    
    if let labelString = response?["test"] as? String {
        println(labelString)  // "yep"
    }
    

    Another way of unwrapping the dictionary:

    if let responseOK = response, let test = responseOK["test"] as? String {
        println(test) // "yep"
    }