Reputation: 211
When accessing a dictionary, such as [String: Any]
, the result type is Optional(Any)
.
When indexing an array of [Any]
, the result type is Any
, and the call can throw a fatal error.
Is there any reason for this difference?
It would be so nice to branch execution with a guard let
, if let
, ?
, and ??
, but instead you have to wrap array indexing in an if data.count <= index
.
Upvotes: 4
Views: 1096
Reputation: 63321
It's ultimately for performance reasons:
Commonly Rejected Changes
...
Strings, Characters, and Collection Types
- Make
Array<T>
subscript access returnT?
orT!
instead ofT
: 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 slowArray
accesses to an unacceptable degree. This topic has come up multiple times before but is very unlikely to be accepted.
Though nothing stops you from rolling your own:
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 = array[safelyIndex: 3]
print(n as Any) // => Optional(3)
Upvotes: 8