When two optionals are assigned to an if let statement, which one gets unwrapped? Swift language

84 Views Asked by At

So if I have some code as written below

func currentWeatherDictionaryfromjsonDictionary (jsonDictionary: [String: AnyObject]? ) -> CurrentWeather? {
    if let currentWeatherama = jsonDictionary?["currently"] as? [String: AnyObject] {...

Now there are two options in the if let statement, the first is jsonDictionary? and the second is the optional returned from accessing the dictionary which is casted to an optional(since the key might not exist).

The question is which optional does this if let statement unwrap, or is it both?

I thought the code will only unwrap the second optional but when i played around in the playground it seemed like jsonDictionary was unwrapped as well. Was wondering if I was right since I am quite new to this. And also where can I find out more about syntax besides the official swift guide, because that guide does not go into specifics in a number of cases.

1

There are 1 best solutions below

2
On

This is an "Optional chain" - a series of commands, which is aborted in the middle if any one of them fails. There are actually four (or maybe five) things happening here:

if let currentWeatherama = jsonDictionary?["currently"] as? [String: AnyObject] 
  • The first ? tests whether jsonDictionary, an Optional, can be safely unwrapped;

  • if that worked, the resulting Dictionary's ["currently"] key's value is fetched, yielding a new Optional;

  • a single command, as? does two things:

    • it tests whether that Optional can be safely unwrapped, and

    • it tests whether the resulting unwrapped value can be safely cast down to a Dictionary;

  • if that worked, the result is assigned to currentWeatherama

If there is any failure along the way, the if test simply fails silently and safely.