println 字典有“可选" [英] println dictionary has "Optional"

查看:42
本文介绍了println 字典有“可选"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个片段:

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

Optional([1, 4, 9, 16, 25])

[75, 43, 103, 87, 12]

[75, 43, 103, 87, 12]

为什么词典案例中有一个可选"?

Why was there an "Optional" in the dictionary case?

推荐答案

Swift 词典正在返回选项以确保安全.如果您尝试访问一个不存在的密钥,那会给您零.

Swift dictionaries are returning optionals for safety. If you try to access a key which does not exists that would give you nil.

您还可以使用下标语法从字典中检索特定键的值.因为可以请求不存在值的键,所以字典的下标返回字典值类型的可选值.如果字典包含请求键的值,则下标返回一个可选值,其中包含该键的现有值.否则下标返回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

来自 Swift 编程语言

使用下标访问任何字典中的单个元素.从字典的下标返回的值是 ValueType 类型吗?— 具有字典 ValueType 基础类型的可选项

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 字典有“可选"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆