为什么print()将我的String打印为可选? [英] 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"])
在这里,dictionary["anotherKey"]
是42
,但是当我在调试器中打印key
时,会看到以下内容:
here, dictionary["anotherKey"]
is 42
but when I print key
in the debugger I see the following:
(lldb) expression print(key)
Optional(42)
那怎么可能?据我了解,String()
构造函数不会不返回一个可选内容(当我编写let key: String
而不是let key: String?
时,编译器不会抱怨).有人可以解释这是怎么回事吗?
How is that possible? To my understanding, the String()
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?
作为旁注,我目前正在使用description()
方法解决此问题.
As a sidenote, I am currently solving this using the description()
method.
推荐答案
这是设计使然-这是Swift的Dictionary
实现方式:
This is by design - it is how Swift's Dictionary
is implemented:
Swift的
Dictionary
类型将其键值下标实现为采用并返回可选类型的下标. [...]Dictionary
类型使用可选的下标类型来对并非每个键都具有值的事实进行建模,并通过为该键分配nil值来提供一种删除键值的方法. (链接到文档)
Swift’s
Dictionary
type implements its key-value subscripting as a subscript that takes and returns an optional type. [...] TheDictionary
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)
您可以将结果包装到if let
构造中,以消除可选的内容,如下所示:
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"]!)
这篇关于为什么print()将我的String打印为可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!