# \[Draft\] Adding Safe indexing to Array

**URL:** <https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767>\
**Category:** Pitches\
**Created:** [March 9, 2018, 6:32pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767 "2018-03-09T18:32:49Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Erica\_Sadun](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/erica_sadun/32/243_2.png) [@Erica\_Sadun](https://forums.swift.org/u/Erica_Sadun)\
**Post date:** [March 9, 2018, 6:32pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/1 "2018-03-09T18:32:49Z")

</div>

_Proposal has been archived_.

---

<div class="post-metadata">

**Author:** ![anon9791410](https://avatars.discourse-cdn.com/v4/letter/a/9fc348/32.png) [@anon9791410](https://forums.swift.org/u/anon9791410)\
**Post date:** [March 9, 2018, 7:07pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/2 "2018-03-09T19:07:32Z")

</div>

I love the idea, and would actually prefer if standard subscripting behavior were more like this.

However, I don't like the conflation of `nil` that will occur when the array holds optionals.

I've gotten around that like this. I'd prefer a subscript but they can't throw errors:

```swift
public extension Array {
  struct OutOfBoundsError: Error {
    public let index: Index
  }
  
  /// - Returns: same as subscript, if index is in bounds
  /// - Throws: Array.OutOfBoundsError
  func getElement(index: Index) throws -> Element {
    guard indices.contains(index)
    else {throw OutOfBoundsError(index: index)}
    
    return self[index]
  }
}

```

---

<div class="post-metadata">

**Author:** ![Erica\_Sadun](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/erica_sadun/32/243_2.png) [@Erica\_Sadun](https://forums.swift.org/u/Erica_Sadun)\
**Post date:** [March 9, 2018, 7:13pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/3 "2018-03-09T19:13:10Z")

</div>

This is officially out of bounds for standard subscripting because of the performance hit among other reasons.

I don't think having to double-unwrap for optionals is any more an issue than if a dict stores optional values.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [March 9, 2018, 7:14pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/4 "2018-03-09T19:14:08Z")

</div>

Erica, I do believe the core team weighed in earlier to say that this subscript should not be called "safe," which in Swift refers specifically to memory safety. The suggested term, if I recall, was "lenient" or "checked."

---

<div class="post-metadata">

**Author:** ![mackoj](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mackoj/32/42395_2.png) [@mackoj](https://forums.swift.org/u/mackoj)\
**Post date:** [March 9, 2018, 7:17pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/5 "2018-03-09T19:17:55Z")

</div>

I have `safe` on `Collection` in my code base and use it help a lot.  
Your proposition will be a great addition to the standard library.

---

<div class="post-metadata">

**Author:** ![Erica\_Sadun](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/erica_sadun/32/243_2.png) [@Erica\_Sadun](https://forums.swift.org/u/Erica_Sadun)\
**Post date:** [March 9, 2018, 7:21pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/6 "2018-03-09T19:21:45Z")

</div>

I didn't see that but that's a great catch. Happy to revise it to `checked` (which I prefer to `lenient`)

---

<div class="post-metadata">

**Author:** ![gwendal.roue](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/gwendal.roue/32/13992_2.png) [@gwendal.roue](https://forums.swift.org/u/gwendal.roue)\
**Post date:** [March 9, 2018, 7:27pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/7 "2018-03-09T19:27:12Z")

</div>

Some will reply that `a[i]` is _already_ checked, and that `a[checked: i]` is redundant.

"Lenient" is hard to read for non-native English speakers that have a limited vocabulary (and code readability is important).

`a[safe: i]` matches what's is everyone's mind (avoid crash), but does not match "safe" as Swift likes to define it (comply to preconditions or crash).

It could live with short and purely made-up subscripts, like `a[at: i]`, or `a[index: i]`. We'd all get used to them, since it's quite a frequent use case.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [March 9, 2018, 7:35pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/8 "2018-03-09T19:35:39Z")

</div>

> [@gwendal.roue](#):
>
> Some will reply that a[i] is already checked, and that a[checked: i] is redundant.
> 
> “Lenient” is hard to read for non-native English speakers that have a limited vocabulary (and code readability is important).

"Lenient" was the top agreed-upon choice, if I recall. It's fine if non-native speakers don't know the word; they can look it up. If it's hard to look up (like an idiomatic expression), then it can be deeply unfair to non-native speakers, but that's not the case here.

We can always bikeshed other options. `ifExists:` would be unambiguous, for example.

---

<div class="post-metadata">

**Author:** ![Jens](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jens/32/12903_2.png) [@Jens](https://forums.swift.org/u/Jens)\
**Post date:** [March 9, 2018, 7:37pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/9 "2018-03-09T19:37:42Z")

</div>

a[valid: i]  
a[existing: i]

---

<div class="post-metadata">

**Author:** ![anon9791410](https://avatars.discourse-cdn.com/v4/letter/a/9fc348/32.png) [@anon9791410](https://forums.swift.org/u/anon9791410)\
**Post date:** [March 9, 2018, 7:39pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/10 "2018-03-09T19:39:39Z")

</div>

Agreed on the "more of an issue". If you don't already take issue with multi-optionals, we won't see eye-to-eye.

---

<div class="post-metadata">

**Author:** ![DevAndArtist](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/devandartist/32/287_2.png) [@DevAndArtist](https://forums.swift.org/u/DevAndArtist)\
**Post date:** [March 9, 2018, 7:45pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/11 "2018-03-09T19:45:33Z")

</div>

My major issue with this pitch is that it uses a subscript instead of a function like `element(at:)` because the discoverability of subscript overloads is quite difficult already (at least Xcode does not provide any autocompletion for subscript labels). But this addition of a checked access to elements is more than welcome.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [March 9, 2018, 7:48pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/12 "2018-03-09T19:48:47Z")

</div>

> [@Jens](#):
>
> a[valid: i]  
> a[existing: i]

Those read to me like you're asserting that `i` is in fact valid or existing, such that if that index is invalid we'd have a precondition failure.

---

<div class="post-metadata">

**Author:** ![Erica\_Sadun](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/erica_sadun/32/243_2.png) [@Erica\_Sadun](https://forums.swift.org/u/Erica_Sadun)\
**Post date:** [March 9, 2018, 8:23pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/13 "2018-03-09T20:23:11Z")

</div>

> [@DevAndArtist](#):
>
> My major issue with this pitch is that it uses a subscript instead of a function like element(at:) because the discoverability of subscript overloads is quite difficult already (at least Xcode does not provide any autocompletion for subscript labels). But this addition of a checked access to elements is more than welcome.

Adding function to alternatives. Thank you

---

<div class="post-metadata">

**Author:** ![Jens](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jens/32/12903_2.png) [@Jens](https://forums.swift.org/u/Jens)\
**Post date:** [March 9, 2018, 8:28pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/14 "2018-03-09T20:28:54Z")

</div>

> [@xwu](#):
>
> a[valid: i]  
> a[existing: i]
> 
> Those read to me like you’re asserting that i is in fact valid or existing, such that if that index is invalid we’d have a precondition failure.

Kind of agree, but wouldn't that be true about eg `a[safe: i]` too?

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [March 9, 2018, 8:29pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/15 "2018-03-09T20:29:29Z")

</div>

> [@Jens](#):
>
> Kind of agree, but wouldn’t that be true about eg a[safe: i] too?

Yup. Hence, something like `ifExists:` (which explicitly disavows knowledge of whether `i` exists or not at the call site).

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [March 9, 2018, 8:43pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/16 "2018-03-09T20:43:43Z")

</div>

I am curious what situations you encounter where this is useful. Personally, I find it far more common to obtain an optional index—such as from `index(where:)`—and want to subscript with it if valid.

Perhaps both scenarios can be handled with one solution:

```swift
subscript(optional idx: Index?) -> Element? {
  if let i = idx, indices.contains(i) { return self[i] }
  return nil
}

```

---

<div class="post-metadata">

**Author:** ![stephencelis](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/stephencelis/32/2675_2.png) [@stephencelis](https://forums.swift.org/u/stephencelis)\
**Post date:** [March 9, 2018, 8:49pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/17 "2018-03-09T20:49:10Z")

</div>

> [@xwu](#):
>
> I do believe the core team weighed in earlier to say that this subscript should not be called “safe,” which in Swift refers specifically to memory safety.

FWIW, Swift uses "safe" to refer to the Optional type several times on its about page: [Swift.org - About Swift](https://swift.org/about/)

---

<div class="post-metadata">

**Author:** ![DeFrenZ](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/defrenz/32/827_2.png) [@DeFrenZ](https://forums.swift.org/u/DeFrenZ)\
**Post date:** [March 9, 2018, 9:36pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/18 "2018-03-09T21:36:22Z")

</div>

Just one question: why on `Array` and not on `Collection`?

---

<div class="post-metadata">

**Author:** ![saagarjha](https://avatars.discourse-cdn.com/v4/letter/s/85f322/32.png) [@saagarjha](https://forums.swift.org/u/saagarjha)\
**Post date:** [March 9, 2018, 9:40pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/19 "2018-03-09T21:40:12Z")

</div>

IIRC, checking whether an index is valid for any arbitrary `Collection` is O(n). `Array` (and `RandomAccessCollection`?) can do this in O(1).

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [March 9, 2018, 9:49pm UTC](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767/20 "2018-03-09T21:49:59Z")

</div>

> [@stephencelis](#):
>
> FWIW, Swift uses “safe” to refer to the Optional type several times on its about page: [Swift.org - About Swift](https://swift.org/about/)

Sure it does; `Optional` is one tool that provides memory safety. The point is not that the proposed method is unsafe--of course it's safe. The point is that the label is supposed to distinguish this subscript from the unlabeled subscript. However, the unlabeled subscript is also safe, and it's a common misconception that it's not--a misconception we're trying not to perpetuate.

[Next page](https://forums.swift.org/t/draft-adding-safe-indexing-to-array/10767.md?page=2)
