實例下標
subscript(_:)
訪問集合元素的連續子範圍。
聲明
subscript(bounds: Range<ClosedRange<Bound>.Index>) -> Slice<ClosedRange<Bound>> { get }
當
Bound
符合 Strideable
並且 Bound.Stride
符合 SignedInteger
時可用。參數
bounds
一係列集合的索引。範圍的邊界必須是集合的有效索引。
概述
例如,將 PartialRangeFrom
範圍表達式與數組一起使用會訪問從範圍表達式開頭到數組結尾的子範圍。
let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2..<5]
print(streetsSlice)
// ["Channing", "Douglas", "Evarts"]
訪問的切片對與原始集合相同的元素使用相同的索引。此示例在 streetsSlice
中搜索切片中的字符串之一,然後在原始數組中使用該索引。
let index = streetsSlice.firstIndex(of: "Evarts")! // 4
print(streets[index])
// "Evarts"
始終使用切片的 startIndex
屬性,而不是假設其索引從特定值開始。嘗試使用切片邊界之外的索引訪問元素可能會導致運行時錯誤,即使該索引對原始集合有效。
print(streetsSlice.startIndex)
// 2
print(streetsSlice[2])
// "Channing"
print(streetsSlice[0])
// error: Index out of bounds
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift ClosedRange index(_:offsetBy:)用法及代碼示例
- Swift ClosedRange ~=(_:_:)用法及代碼示例
- Swift ClosedRange clamped(to:)用法及代碼示例
- Swift ClosedRange relative(to:)用法及代碼示例
- Swift ClosedRange ==(_:_:)用法及代碼示例
- Swift ClosedRange.Index ..<(_:)用法及代碼示例
- Swift ClosedRange.Index ..<(_:_:)用法及代碼示例
- Swift ClosedRange用法及代碼示例
- Swift ClosedRange.Index ...(_:_:)用法及代碼示例
- Swift ClosedRange.Index ...(_:)用法及代碼示例
- Swift CollectionDifference firstIndex(of:)用法及代碼示例
- Swift Collection prefix(upTo:)用法及代碼示例
- Swift ContiguousArray forEach(_:)用法及代碼示例
- Swift CollectionOfOne contains(_:)用法及代碼示例
- Swift Collection first用法及代碼示例
- Swift Character lowercased()用法及代碼示例
- Swift ContiguousArray insert(contentsOf:at:)用法及代碼示例
- Swift CollectionOfOne compactMap(_:)用法及代碼示例
- Swift CollectionDifference contains(where:)用法及代碼示例
- Swift CollectionOfOne last(where:)用法及代碼示例
- Swift Collection dropLast(_:)用法及代碼示例
- Swift ContiguousArray reserveCapacity(_:)用法及代碼示例
- Swift Comparable ...(_:)用法及代碼示例
- Swift ContiguousArray lexicographicallyPrecedes(_:)用法及代碼示例
- Swift ContiguousArray elementsEqual(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 ClosedRange subscript(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。