为什么 Swift 中的数组索引不是 return 的可选值?

Why does array indexing in Swift not return an optional value?

访问字典时,例如 [String:Any],结果类型为 Optional(Any)。

索引 [Any] 的数组时,结果类型为 Any,调用可能会引发致命错误。

这种差异有什么原因吗?

用 guard let、if let、? 和 ?? 来分支执行会很好,但是你必须将数组索引包装在 if data.count <= index.

归根结底是出于性能原因:

Commonly Rejected Changes

...

Strings, Characters, and Collection Types

  • Make Array<T> subscript access return T? or T! instead of T: The current array behavior is intentional, as it accurately reflects the fact that out-of-bounds array access is a logic error. Changing the current behavior would slow Array accesses to an unacceptable degree. This topic has come up multiple times before but is very unlikely to be accepted.

https://github.com/apple/swift-evolution/blob/master/commonly_proposed.md#strings-characters-and-collection-types

虽然没有什么能阻止你自己动手:

extension Collection {
    subscript(safelyIndex i: Index) -> Element? {
        get {
            guard self.indices.contains(i) else { return nil }
            return self[i]
        }
    }
}

let array = Array(0...10)
let n = [safelyIndex: 3]
print(n as Any) // => Optional(3)