Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Runtime-safe array subscripting #133

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 37 additions & 0 deletions proposals/XXXX-runtime-safe-array-subscripting.md
@@ -0,0 +1,37 @@
# Runtime-safe array subscripting

* Proposal: [SE-NNNN](https://github.com/apple/swift-evolution/blob/master/proposals/NNNN-name.md)
* Author(s): [Rudolf Adamkovič](https://github.com/salutis)
* Status: **Awaiting review**
* Review manager: TBD

## Introduction

Add an alternative way to subscript arrays where out-of-bounds runtime errors are converted to `nil`.

Swift-evolution thread: [Optional safe subscripting for arrays](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160111/006826.html)

## Proposed solution

Allow to safely index into arrays returning `Element?`:

```swift
// Sample data
var array = [0, 1, 2]

// Setting values
array[ifExists: 0] // same as array[0]
array[ifExists: 3] // out of bounds, evaluates to nil

// Getting values
array[ifExists: 0] = 42 // same as array[0] = 42
array[ifExists: 3] = 42 // out of bounds, no operation
```

## Impact on existing code

No existing code is affected.

## Alternatives considered

* Extend the `CollectionType` or `Indexable` protocol instead the `Array`