用法一
實例下標
subscript(_:)
訪問集合元素的連續子範圍。
必需的。提供的默認實現。
聲明
override subscript(bounds: Range<Self.Index>) -> Self.SubSequence { get set }
參數
bounds
一係列集合的索引。範圍的邊界必須是集合的有效索引。
概述
訪問的切片對與原始集合相同的元素使用相同的索引。始終使用切片的 startIndex
屬性,而不是假設其索引從特定值開始。
此示例演示獲取字符串數組的切片,查找切片中字符串之一的索引,然後在原始數組中使用該索引。
var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2 ..< streets.endIndex]
print(streetsSlice)
// Prints "["Channing", "Douglas", "Evarts"]"
let index = streetsSlice.firstIndex(of: "Evarts") // 4
streets[index!] = "Eustace"
print(streets[index!])
// Prints "Eustace"
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
用法二
實例下標
subscript(_:)
訪問指定位置的元素。
必需的。提供的默認實現。
聲明
override subscript(position: Self.Index) -> Self.Element { get set }
參數
position
要訪問的元素的位置。
position
必須是不等於endIndex
屬性的集合的有效索引。
概述
例如,您可以使用其下標替換數組的元素。
var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
streets[1] = "Butler"
print(streets[1])
// Prints "Butler"
您可以使用集合的結束索引以外的任何有效索引為集合下標。結束索引是指在集合的最後一個元素之後的位置,因此它與元素不對應。
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift MutableCollection sort(by:)用法及代碼示例
- Swift MutableCollection shuffle()用法及代碼示例
- Swift MutableCollection sort()用法及代碼示例
- Swift MutableCollection shuffle(using:)用法及代碼示例
- Swift MutableCollection partition(by:)用法及代碼示例
- Swift MutableCollection reverse()用法及代碼示例
- Swift MutableCollection用法及代碼示例
- Swift Mirror description用法及代碼示例
- Swift MemoryLayout alignment(ofValue:)用法及代碼示例
- Swift MemoryLayout用法及代碼示例
- Swift Mirror.Children用法及代碼示例
- Swift Mirror.AncestorRepresentation.customized(_:)用法及代碼示例
- Swift ManagedBufferPointer用法及代碼示例
- Swift MemoryLayout stride(ofValue:)用法及代碼示例
- Swift MemoryLayout offset(of:)用法及代碼示例
- Swift Mirror descendant(_:_:)用法及代碼示例
- Swift MemoryLayout size(ofValue:)用法及代碼示例
- Swift Mirror用法及代碼示例
- Swift KeyValuePairs flatMap(_:)用法及代碼示例
- Swift String.UTF8View first用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Optional.Publisher reduce(_:_:)用法及代碼示例
- Swift Int8 ~(_:)用法及代碼示例
- Swift SetAlgebra isStrictSubset(of:)用法及代碼示例
- Swift UInt +(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 MutableCollection subscript(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。