A collection that supports subscript assignment.
- Xcode 8.0+
- Swift Standard Library
Collections that conform to
Mutable gain the ability to change the value of their elements. This example shows how you can modify one of the names in an array of students.
In addition to changing the value of an individual element, you can also change the values of a slice of elements in a mutable collection. For example, you can sort part of a mutable collection by calling the mutable
sort() method on a subscripted subsequence. Here’s an example that sorts the first half of an array of integers:
Mutable protocol allows changing the values of a collection’s elements but not the length of the collection itself. For operations that require adding or removing elements, see the
Range protocol instead.
Conforming to the MutableCollection Protocol
To add conformance to the
Mutable protocol to your own custom collection, upgrade your type’s subscript to support both read and write access.
A value stored into a subscript of a
Mutable instance must subsequently be accessible at that same position. That is, for a mutable collection instance
i, and value
x, the two sets of assignments in the following code sample must be equivalent: