協議
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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。