Subscript

subscript(_:)

Accesses the element at the specified position.

Required. Default implementation provided.

Declaration

subscript(position: Self.Index) -> Self.Element { get }

Parameters

position

The position of the element to access. position must be a valid index of the collection that is not equal to the endIndex property.

Discussion

The following example accesses an element of an array through its subscript to print its value:

var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
print(streets[1])
// Prints "Bryant"

You can subscript a collection with any valid index other than the collection’s end index. The end index refers to the position one past the last element of a collection, so it doesn’t correspond with an element.

Complexity: O(1)

Default Implementations

Collection Implementations

subscript<R>(R) -> Self.SubSequence

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

subscript(Range<Self.Index>) -> Slice<Self>

Accesses a contiguous subrange of the collection’s elements.