Required Instance Subscriptswift 6.0.1Swift

    subscript(_:)

    Accesses a contiguous subrange of the collection’s elements.

    subscript(bounds: Range<Self.Index>) -> Self.SubSequence { get }

    Parameters

    bounds

    A range of the collection’s indices. The bounds of the range must be valid indices of the 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..<5]
    print(streetsSlice)
    // ["Channing", "Douglas", "Evarts"]

    The accessed slice uses the same indices for the same elements as the original collection. 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
    print(streets[index])
    // "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 may result in a runtime error, even if that index is valid for the original collection.

    print(streetsSlice.startIndex)
    // 2
    print(streetsSlice[2])
    // "Channing"
    
    print(streetsSlice[0])
    // error: Index out of bounds

    Other requirements

    View members

    Hide members

    This section is hidden by default because it contains too many (17) members.

    Type members

    Instance members

    Citizens in Swift

    Restated by

    Default implementations

    Available in Cxx

    Default implementations

    • subscript(Int) -> Self.Element

      A C++ implementation of the subscript might be more performant. This overload should only be used if the C++ type does not define operator[].