Swift dictionary with assigned nil value can be conditionally bind in if let statement

108 Views Asked by At

Can you explain this Swift code

If I assign nil value for "a" key and then use if let statement this nil value will be unwrapped as nil and can be printed

import Foundation
var dictionary = ["a": nil, "b": "Costam", "c": nil]
dictionary.updateValue(nil, forKey: "a")

if let value = dictionary["b"] { 
   print("Some value: ", value)
}

print(dictionary.keys)

And to prevent this behaviour I need to add typecasting to String?

import Foundation
var dictionary = ["a": nil, "b": "Costam", "c": nil]
dictionary.updateValue(nil, forKey: "a")

if let value = dictionary["b"] as? String { 
   print("Some value: ", value)
}

print(dictionary.keys)
1

There are 1 best solutions below

0
On

If I put your first snippet into a playground, I see the warning: "Expression implicitly coerced from 'String?' to 'Any'". So, nothing is being automatically unwrapped and, in fact, if I get rid of the warning by force unwrapping, it crashes (as expected).

Your dictionary data type is [String:String?] and value is String?. When you don't tell the compiler what you want, it decides on something relatively safe. Only when you're explicit does it check if the specified conversion can work.