协议
Mutable
MutableCollection
支持下标赋值的集合。
声明
protocol MutableCollection<Element> : Collection where Self.SubSequence : MutableCollection
概述
符合MutableCollection
的集合能够更改其元素的值。此示例说明如何修改学生数组中的一个姓名。
var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
students[i] = "Max"
}
print(students)
// Prints "["Ben", "Ivy", "Jordell", "Max"]"
除了更改单个元素的值之外,您还可以更改可变集合中元素切片的值。例如,您可以通过在下标子序列上调用可变 sort()
方法来对可变集合的 part
进行排序。这是一个对整数数组的前半部分进行排序的示例:
var numbers = [15, 40, 10, 30, 60, 25, 5, 100]
numbers[0..<4].sort()
print(numbers)
// Prints "[10, 15, 30, 40, 60, 25, 5, 100]"
MutableCollection
协议允许更改集合元素的值,但不能更改集合本身的长度。对于需要添加或删除元素的操作,请参阅RangeReplaceableCollection
协议。
符合MutableCollection 协议
要将MutableCollection
协议的一致性添加到您自己的自定义集合中,请升级您的类型的下标以支持读取和写入访问。
存储在MutableCollection
实例的下标中的值随后必须可以在同一位置访问。也就是说,对于可变集合实例 a
、索引 i
和值 x
,以下代码示例中的两组赋值必须相等:
a[i] = x
let y = a[i]
// Must be equivalent to:
a[i] = x
let y = x
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相关用法
- Swift MutableCollection partition(by:)用法及代码示例
- Swift MutableCollection subscript(_:)用法及代码示例
- Swift MutableCollection sort(by:)用法及代码示例
- Swift MutableCollection shuffle()用法及代码示例
- Swift MutableCollection reverse()用法及代码示例
- Swift MutableCollection sort()用法及代码示例
- Swift MutableCollection shuffle(using:)用法及代码示例
- 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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。