phi phi - 6 months ago 3x
Swift Question

Why print() is printing my String as an optional?

I have a dictionary and I want to use some of its values as a key for another dictionary:

let key: String = String(dictionary["anotherKey"])

but when I print
in the debugger I see the following:

(lldb) expression print(key)

How is that possible? To my understanding, the
constructor does not return an optional (and the compiler does not complain when I write
let key: String
instead of
let key: String?
). Can someone explain what's going on here?

As a sidenote, I am currently solving this using the


This is by design - it is how Swift's Dictionary is implemented:

Swift’s Dictionary type implements its key-value subscripting as a subscript that takes and returns an optional type. [...] The Dictionary type uses an optional subscript type to model the fact that not every key will have a value, and to give a way to delete a value for a key by assigning a nil value for that key. (link to documentation)

You can unwrap the result in an if let construct to get rid of optional, like this:

if let val = dictionary["anotherKey"] {
    ... // Here, val is not optional

If you are certain that the value is there, for example, because you put it into the dictionary a few steps before, you could force unwrapping with the ! operator as well:

let key: String = String(dictionary["anotherKey"]!)