swift - println 字典有 "Optional"

标签 swift

考虑这个片段:

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

From the Swift Standard Library Reference

关于swift - println 字典有 "Optional",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25979969/

相关文章:

ios - Swift 中的 "' CGFloat ' is not convertible to ' Double '"错误(iOS)

ios - 为什么在添加 Alamofire 框架时会出现很多错误?

ios - Swift 语言中的 _cmd

ios - 联系人框架等同于 ABAddressBook.ABAddressBookRegisterExternalChangeCallback

swift - 检查坐标是否在 KML 多边形内

swift - 在场景之间转换时保留循环问题

iOS:解析 DNS SRV 记录

ios - 给定不同字段的键,从字典中获取值

ios - 我可以在 Swift 中构建 watch 应用程序并将其添加到不是在 Swift 中构建的 iOS 应用程序吗?

objective-c - 将一个常量变量从 Objective-C 暴露给 Swift