> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swift/collections/collection/collection-safe-index.md).

# 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](/ios/swift/subscripts.md)
  {% endtab %}
  {% endtabs %}
