# collection\[safe: index]

{% tabs %}
{% tab title="code" %}

```swift
// avoid index out-of-range
extension Collection { 
    /// return the element at the index if it is within range,
    /// otherwise nil.
    ///
    /// Example:
    /// `collection[safe: 20]`
    subscript(safe index: Index) -> Element? { 
        return indices.contains(index) ? self[index] : nil 
    } 
}
```

{% endtab %}

{% tab title="📗 參考" %}

* Test-Driven Development in Swift (2021), p. 59
  {% endtab %}

{% tab title="👥 相關" %}

* [subscripts](https://lochiwei.gitbook.io/ios/swift/subscripts "mention")
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/ios/swift/collections/collection/collection-safe-index.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
