用法一
实例下标
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(_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。