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

后端 未结 4 1911
醉酒成梦
醉酒成梦 2021-01-23 02:41

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\"])

4条回答
  •  迷失自我
    2021-01-23 03:29

    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"]!)
    

提交回复
热议问题