Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'String' does not conform to protocol 'NSCopying' error when downcast AnyObject to String

I'm tring to parse a JSON format like this:

{ 
    "key_1" : {
        "key_2" : "value"
    }

}

and then assign "value" to a variable.

Here is my code:

var variableShouldBeAssigned: String
if let x = (jsonResult["key_1"]? as? NSDictionary) {
    if let y = (x["key_2"]? as? String) {
        variableShouldBeAssigned = y
    }
}

However, an error occurs when I try to downcast from x["key_2"]? to a String, but it's fine to downcast from jsonResult["key_1"]? to an NSDictionary.

I can solve the error by using x["key_2"] to replace x["key_2"]?, but I don't really know why it only works for jsonResult["key_1"]?.

Can anybody tell me the reason?

like image 227
user3429911 Avatar asked Jul 28 '14 03:07

user3429911


2 Answers

String does not conform to NSCopying, but surely NSString does! Also, going from NSString to String is instantaneously implied...

So I would say try something like this... Change String to NSString

here is a sample, assuming that you handle the jsonResult as a NSDictionary...

func giveDictionary(jsonResult:NSDictionary) -> String?
{

    if let x = (jsonResult["key_1"]? as? NSDictionary)
    {
        if let y = (x["key_2"]? as? NSString)
        {
            return y
        }
    }
    return nil
}
like image 61
Ethan Avatar answered Nov 17 '22 01:11

Ethan


You can simplify all your type checking by using a Swift dictionary at the beginning:

var variableShouldBeAssigned: String
if let dict = jsonResult as? [String:[String:String]] {
    if let key1Dict = dict["key_1"] {
        if let value = key1Dict["key_2"] {
            variableShouldBeAssigned = value
        }
    }
}

In fact, you can even combine the two last if statements:

var variableShouldBeAssigned: String
if let dict = jsonResult as? [String:[String:String]] {
    if let value = dict["key_1"]?["key_2"] {
       variableShouldBeAssigned = value
    }
}

In general, you should using Swift Dictionaries instead of NSDictionary

like image 26
drewag Avatar answered Nov 17 '22 03:11

drewag