Search code examples
swiftdictionaryoption-typeforced-unwrapping

What happens when a Swift "if let ... " on a Dictionary key fails?


I've got a dictionary that's deliberately setup to fail when there's no pre-existing value in it matching a certain criteria.

All other times, this command will work, but for one time. I'm hoping I'm doing this right... that the fail means nothing happens. That I don't need an else or any other contingency code.

But is that right?

if let myTestKonstant = myDictionary[Int(store.itemID)]{
         // successful assignment code here   
        }

// where I'm hoping a failure to assign falls through to...

Solution

  • It is not completely right, the problem is that the conversion to int is also optional. For example, this would crash (or rather, you would get a compiling error):

    let myDictionary = [3: "3"]
    let itemID = "b"
    if let myTestKonstant = myDictionary[Int(itemID)] {
        print(myTestKonstant)
    }  
    

    This would be the save way:

    if let itemKey = Int(itemID), let myTestKonstant = myDictionary[itemKey] {
        print(myTestKonstant)
    }
    

    UPDATE

    So it is clearer, I will explain what would happen in different cases:

    1. itemID can't be converted to an Int: This would mean that itemKey will be nil, hence, the second part would't even be tested and the content of the if wouldn't be executed.

    2. itemID can be converted to an Int, but it is not an existing key: In this case itemKey would be set to the Int itemID gets converted to. Then, the second statement would be tested, but since itemKey would not be found as an existing key, myDictionary[itemKey] would return nil and again, the content of the if would not be executed.

    3. itemID can be converted to an Int that exists as key of the dictionary. Like in the previous case, itemKey will be set, and since the key is found, myTestKonstant will be filled and the content of the if will be executed, unless the corresponding value of the key is nil (like in [3: nil]).