Tuesday, 15 July 2014

ios - Swift clarification about optional with NSDictionary and valueForKey -


I'm trying to learn swift porting in my obz-c code which manages HTText, but when I In response to JSUN, I have to try to use NSDictionary.

JSON example:

  {response = {id = 1234; Name = a2b3n4h5lkl3; }; }  

I get the HttpRequest full handler

  (dictionary: NSDictionary ?, error: NSERR?) - & gt; From zero  

I want to get some values ​​from NSDictionary? And save them to a var:

  Feedback = Dictionary! .valueForKey ("feedback") as? NSDictionary println (responseDictionary!) // contains the information correctly if (responseDictionary!! Count> 0) {var testStringAccessId: NSString? = ResponseDictionary! .valueForKey ("id")! Like? NSString println (testStringAccessId) / print nil println (responseDictionary! .valueForKey ("id")) // Print the correct string if StressAccessed = ResponseDiskin! .valueForKey ("id")! Like? NSString {self.accessID = stringAccessId} other {println ("error no access id") // complete here (success: wrong) return / exit function with error}}  

I tried many combinations but maybe I'm missing something in alternative use. The strange thing is that if I comment back to the case of error and try to get another value from NSDictionary then it's okay , Such as:

  if string is written = copy Saddiskactor! .valueForKey ("name")! Like? NSString {self.accessname = stringAccessname // I get the correct value saved in the variable} other {println ("error does not enter NAME") completion (success: incorrect) returns}  

Also please help?

Thanks alay

Resolved :

Use NSNumber instead of NSString. Thank you for Jasper

As you have said right in your question after editing, your ID is a String (or NSSTING), which is trying to insert a string in any NSN, it will return the value of zero.

  var testStringAccessId: NSNumber? = ResponseDictionary! .valueForKey ("id")! Like? NSNM  

Here is the right syntax for using.

Maybe I would like to add that you want to open the dictionary before checking it. You want to add a check there, what if you can not connect to the internet, or when your API crashes? There are very few times where you actually ! Using


No comments:

Post a Comment