'String' type does not match NSCopying protocol error while suppressing AnyObject in String

I am trying to parse the JSON format as follows:

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

and then assign the variable "value" 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 disconnect from x["key_2"]? to String, but is it fine to reset with jsonResult["key_1"]? in NSDictionary.

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

Can someone tell me the reason?

+6
source share
2 answers

The string does not match NSCopying, but certainly NSString does! In addition, instantly implies a transition from NSString to String ...

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

Here is an example assuming you are treating jsonResult as an 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 } 
+4
source

You can simplify all type checking with the 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 last two 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 use Swift Dictionaries instead of NSDictionary

+3
source

Source: https://habr.com/ru/post/972936/


All Articles