考虑这个片段:
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
println(interestingNumbers["Square"])
let individualScores = [75, 43, 103, 87, 12]
println(individualScores)
控制台输出:
可选([1, 4, 9, 16, 25])
[75、43、103、87、12]
为什么字典里有一个“Optional”?
最佳答案
为了安全起见,Swift 字典正在返回选项。如果您尝试访问不存在的 key ,则会返回 nil。
You can also use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil
From The Swift Programming Language
和
Use subscripting to access the individual elements in any dictionary. The value returned from a dictionary's subscript is of type ValueType? — an optional with an underlying type of the dictionary’s ValueType
关于swift - println 字典有 "Optional",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25979969/