Generic Subscript


Accesses the contiguous subrange of the collection’s elements specified by a range expression.


subscript<R>(r: R) -> Range<Bound> where R : RangeExpression, Self.Index == R.Bound { get }
Available when Bound conforms to Strideable and Bound.Stride conforms to SignedInteger.



A range of the collection’s indices. The bounds of the range must be valid indices of the collection.


The range expression is converted to a concrete subrange relative to this collection. For example, using a PartialRangeFrom range expression with an array accesses the subrange from the start of the range expression until the end of the array.

let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2...]
// ["Channing", "Douglas", "Evarts"]

The accessed slice uses the same indices for the same elements as the original collection uses. This example searches streetsSlice for one of the strings in the slice, and then uses that index in the original array.

let index = streetsSlice.firstIndex(of: "Evarts")    // 4
// "Evarts"

Always use the slice’s startIndex property instead of assuming that its indices start at a particular value. Attempting to access an element by using an index outside the bounds of the slice’s indices may result in a runtime error, even if that index is valid for the original collection.

// 2
// "Channing"

// error: Index out of bounds

Complexity: O(1)

See Also

Accessing Elements

var first: Bound?

The first element of the collection.

var last: Bound?

The last element of the collection.

subscript(Range<Bound>.Index) -> Range<Bound>.Element

Accesses the element at specified position.

subscript(Range<Range<Bound>.Index>) -> Range<Bound>

Accesses the subsequence bounded by the given range.

subscript((UnboundedRange_) -> ()) -> Range<Bound>
func randomElement() -> Bound?

Returns a random element of the collection.

func randomElement<T>(using: inout T) -> Bound?

Returns a random element of the collection, using the given generator as a source for randomness.