Security does not expand

I am trying to process a JSON object using the guard statement to expand it and apply to the type I want, but the value is still saved as optional.

 guard let json = try? JSONSerialization.jsonObject(with: data) as? [String:Any] else { break } let result = json["Result"] // Error: Value of optional type '[String:Any]?' not unwrapped 

Did I miss something?

+5
source share
1 answer
 try? JSONSerialization.jsonObject(with: data) as? [String:Any] 

interpreted as

 try? (JSONSerialization.jsonObject(with: data) as? [String:Any]) 

what makes it "double optional" like [String:Any]?? . Optional binding removes only one level, so json is of type [String:Any]?

The problem is solved by setting parentheses:

 guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String:Any] else { break } 

And just for fun: Another (less obvious ?, obfuscation?) Solution is to use a matching pattern with a double optional pattern:

 guard case let json?? = try? JSONSerialization.jsonObject(with: data) as? [String:Any] else { break } 
+10
source

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


All Articles