Swift 中 "Accessing Subscripts of Optional Type" 的说明

Clarification for "Accessing Subscripts of Optional Type" in Swift

有人可以解释为什么可选链接是在非可选子数组上完成的。 Apple的Swift文档给出的解释让我很困惑:

If a subscript returns a value of optional type—such as the key subscript of Swift’s Dictionary type—place a question mark after the subscript’s closing bracket to chain on its optional return value:

文档示例:

var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
testScores["Dave"]?[0] = 91
testScores["Bev"]?[0]++
testScores["Brian"]?[0] = 72
// the "Dave" array is now [91, 82, 84] and the "Bev" array is now [80, 94, 81]

声明不应该是:

var testScores:[String:Array<Int>?] = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]

这是关于 Accessing Subscripts of Optional Type

的 Apple Swift 文档部分

我认为这里的混淆是字典 testScores 是非可选的,但值 testScores["Dave"] 是可选的。原因是任何时候你从字典中请求一个值,它可能存在……也可能不存在。从字典返回本质上是一个可选操作。考虑一下如果您说 testScores["Fred"]--这将 return 编辑 nil。由于可以 return 一个对象,或者可以 return nil,下标 Dictionary of Arrays returns 一个可选的 Array。因此,return 类型 ([Int]?) 不同于值类型 ([Int])。

你给出的第二个例子略有不同。在您的第二个示例中, return 类型不是可选的,元素 本身 是可选的。这意味着你可以有这样的东西:

let array1 = [0, 1, 2]
let array2: [Int]? = nil
let dict = ["Fred": array1, "Wilma": array2] // [String: [Int]?]

在那种情况下,您实际上有 两层 可选值(一个可选的可选整数数组,[Int]??,并且需要像这样访问一个元素:

let x = dict["Fred"]??[0]