MutableCollection

protocol MutableCollection

A collection that supports subscript assignment.

Inheritance Collection
Conforming Types Array, ArraySlice, CollectionOfOne, ContiguousArray, EmptyCollection, UnsafeMutableBufferPointer, UnsafeMutableRawBufferPointer
Associated Types
associatedtype Element
associatedtype Index
associatedtype SubSequence

Collections that conform to MutableCollection 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.

var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
    students[i] = "Max"
}
print(students)
// Prints "["Ben", "Ivy", "Jordell", "Max"]"

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:

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]"

The MutableCollection 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 RangeReplaceableCollection protocol instead.

Conforming to the MutableCollection Protocol

To add conformance to the MutableCollection 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 MutableCollection instance must subsequently be accessible at that same position. That is, for a mutable collection instance a, index i, and value x, the two sets of assignments in the following code sample must be equivalent:

a[i] = x
let y = a[i]

// Must be equivalent to:
a[i] = x
let y = x

Subscripts

subscript subscript(bounds:) Required

Accesses a contiguous subrange of the collection's elements.

The accessed slice uses the same indices for the same elements as the original collection. Always use the slice's startIndex property instead of assuming that its indices start at a particular value.

This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array.

let 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"
  • Parameter bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Complexity: O(1)

Declaration

override subscript(bounds: Range<Self.Index>) -> Self.SubSequence
subscript subscript(position:) Required

Accesses the element at the specified position.

For example, you can replace an element of an array by using its subscript.

var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
streets[1] = "Butler"
print(streets[1])
// Prints "Butler"

You can subscript a collection with any valid index other than the collection's end index. The end index refers to the position one past the last element of a collection, so it doesn't correspond with an element.

  • Parameter position: The position of the element to access. position must be a valid index of the collection that is not equal to the endIndex property.

Complexity: O(1)

Declaration

override subscript(position: Self.Index) -> Self.Element

Instance Methods

func partition(by belongsInSecondPartition: (Self.Element) throws -> Bool) rethrows -> Self.Index Required

Reorders the elements of the collection such that all the elements that match the given predicate are after all the elements that don't match.

After partitioning a collection, there is a pivot index p where no element before p satisfies the belongsInSecondPartition predicate and every element at or after p satisfies belongsInSecondPartition.

In the following example, an array of numbers is partitioned by a predicate that matches elements greater than 30.

var numbers = [30, 40, 20, 30, 30, 60, 10]
let p = numbers.partition(by: { $0 > 30 })
// p == 5
// numbers == [30, 10, 20, 30, 30, 60, 40]

The numbers array is now arranged in two partitions. The first partition, numbers[..<p], is made up of the elements that are not greater than 30. The second partition, numbers[p...], is made up of the elements that are greater than 30.

let first = numbers[..<p]
// first == [30, 10, 20, 30, 30]
let second = numbers[p...]
// second == [60, 40]
  • Parameter belongsInSecondPartition: A predicate used to partition the collection. All elements satisfying this predicate are ordered after all elements not satisfying it.

Complexity: O(n), where n is the length of the collection.

Declaration

mutating func partition(by belongsInSecondPartition: (Self.Element) throws -> Bool) rethrows -> Self.Index
func swapAt(_ i: Self.Index, _ j: Self.Index) Required

Exchanges the values at the specified indices of the collection.

Both parameters must be valid indices of the collection and not equal to endIndex. Passing the same index as both i and j has no effect.

Complexity: O(1)

Declaration

mutating func swapAt(_ i: Self.Index, _ j: Self.Index)
func withContiguousMutableStorageIfAvailable(_ body: (inout UnsafeMutableBufferPointer<Self.Element>) throws -> R) rethrows -> R? Required

Call body(p), where p is a pointer to the collection's mutable contiguous storage. If no such storage exists, it is first created. If the collection does not support an internal representation in a form of mutable contiguous storage, body is not called and nil is returned.

Often, the optimizer can eliminate bounds- and uniqueness-checks within an algorithm, but when that fails, invoking the same algorithm on body\ 's argument lets you trade safety for speed.

Declaration

mutating func withContiguousMutableStorageIfAvailable<R>(_ body: (inout UnsafeMutableBufferPointer<Self.Element>) throws -> R) rethrows -> R?

Default Implementations

var count

The number of elements in the collection.

To check whether a collection is empty, use its isEmpty property instead of comparing count to zero. Unless the collection guarantees random-access performance, calculating count can be an O(n) operation.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

var count: Int
func distance(from start: Self.Index, to end: Self.Index) -> Int

Returns the distance between two indices.

Unless the collection conforms to the BidirectionalCollection protocol, start must be less than or equal to end.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the resulting distance.

Declaration

@inlinable public func distance(from start: Self.Index, to end: Self.Index) -> Int
func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence

Returns a subsequence by skipping elements while predicate returns true and returning the remaining elements.

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be skipped or false if it should be included. Once the predicate returns false it will not be called again.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
func dropFirst(_ k: Int = 1) -> Self.SubSequence

Returns a subsequence containing all but the given number of initial elements.

If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst(2))
// Prints "[3, 4, 5]"
print(numbers.dropFirst(10))
// Prints "[]"
  • Parameter k: The number of elements to drop from the beginning of the collection. k must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to drop from the beginning of the collection.

Declaration

@inlinable public func dropFirst(_ k: Int = 1) -> Self.SubSequence
func dropLast(_ k: Int = 1) -> Self.SubSequence

Returns a subsequence containing all but the specified number of final elements.

If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"
  • Parameter k: The number of elements to drop off the end of the collection. k must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

@inlinable public func dropLast(_ k: Int = 1) -> Self.SubSequence
var first

The first element of the collection.

If the collection is empty, the value of this property is nil.

let numbers = [10, 20, 30, 40, 50]
if let firstNumber = numbers.first {
    print(firstNumber)
}
// Prints "10"

Declaration

var first: Self.Element?
func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?

Returns the first index in which an element of the collection satisfies the given predicate.

You can use the predicate to find an element of a type that doesn't conform to the Equatable protocol or to find an element that matches particular criteria. Here's an example that finds a student name that begins with the letter "A":

let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.firstIndex(where: { $0.hasPrefix("A") }) {
    print("\(students[i]) starts with 'A'!")
}
// Prints "Abena starts with 'A'!"
  • Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?
func formIndex(_ i: inout Self.Index, offsetBy distance: Int)

Offsets the given index by the specified distance.

The value passed as distance must not offset i beyond the bounds of the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func formIndex(_ i: inout Self.Index, offsetBy distance: Int)
func formIndex(_ i: inout Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool

Offsets the given index by the specified distance, or so that it equals the given limiting index.

The value passed as distance must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func formIndex(_ i: inout Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool
func formIndex(after i: inout Self.Index)

Replaces the given index with its successor.

  • Parameter i: A valid index of the collection. i must be less than endIndex.

Declaration

@inlinable public func formIndex(after i: inout Self.Index)
func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index

Returns an index that is the specified distance from the given index.

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position.

let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 4)
print(s[i])
// Prints "t"

The value passed as distance must not offset i beyond the bounds of the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index
func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index?

Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position. The operation doesn't require going beyond the limiting s.endIndex value, so it succeeds.

let s = "Swift"
if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
    print(s[i])
}
// Prints "t"

The next example attempts to retrieve an index six positions from s.startIndex but fails, because that distance is beyond the index passed as limit.

let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
print(j)
// Prints "nil"

The value passed as distance must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index?
var isEmpty

A Boolean value indicating whether the collection is empty.

When you need to check whether your collection is empty, use the isEmpty property instead of checking that the count property is equal to zero. For collections that don't conform to RandomAccessCollection, accessing the count property iterates through the elements of the collection.

let horseName = "Silver"
if horseName.isEmpty {
    print("I've been through the desert on a horse with no name.")
} else {
    print("Hi ho, \(horseName)!")
}
// Prints "Hi ho, Silver!")

Complexity: O(1)

Declaration

var isEmpty: Bool
func map(_ transform: (Self.Element) throws -> T) rethrows -> [T]

Returns an array containing the results of mapping the given closure over the sequence's elements.

In this example, map is used first to convert the names in the array to lowercase strings and then to count their characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
// 'letterCounts' == [6, 6, 3, 4]
  • Parameter transform: A mapping closure. transform accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type.

Declaration

@inlinable public func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
func prefix(_ maxLength: Int) -> Self.SubSequence

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to select from the beginning of the collection.

Declaration

@inlinable public func prefix(_ maxLength: Int) -> Self.SubSequence
func prefix(through position: Self.Index) -> Self.SubSequence

Returns a subsequence from the start of the collection through the specified position.

The resulting subsequence includes the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, and including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(through: i))
}
// Prints "[10, 20, 30, 40]"

Using the prefix(through:) method is equivalent to using a partial closed range as the collection's subscript. The subscript notation is preferred over prefix(through:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[...i])
}
// Prints "[10, 20, 30, 40]"
  • Parameter end: The index of the last element to include in the resulting subsequence. end must be a valid index of the collection that is not equal to the endIndex property.

Complexity: O(1)

Declaration

@inlinable public func prefix(through position: Self.Index) -> Self.SubSequence
func prefix(upTo end: Self.Index) -> Self.SubSequence

Returns a subsequence from the start of the collection up to, but not including, the specified position.

The resulting subsequence does not include the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, but not including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(upTo: i))
}
// Prints "[10, 20, 30]"

Passing the collection's starting index as the end parameter results in an empty subsequence.

print(numbers.prefix(upTo: numbers.startIndex))
// Prints "[]"

Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred over prefix(upTo:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[..<i])
}
// Prints "[10, 20, 30]"
  • Parameter end: The "past the end" index of the resulting subsequence. end must be a valid index of the collection.

Complexity: O(1)

Declaration

@inlinable public func prefix(upTo end: Self.Index) -> Self.SubSequence
func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence

Returns a subsequence containing the initial elements until predicate returns false and skipping the remaining elements.

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be included or false if it should be excluded. Once the predicate returns false it will not be called again.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
func randomElement() -> Self.Element?

Returns a random element of the collection.

Call randomElement() to select a random element from an array or another collection. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement()!
// randomName == "Amani"

This method is equivalent to calling randomElement(using:), passing in the system's default random generator.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

@inlinable public func randomElement() -> Self.Element?
func randomElement(using generator: inout T) -> Self.Element?

Returns a random element of the collection, using the given generator as a source for randomness.

Call randomElement(using:) to select a random element from an array or another collection when you are using a custom random number generator. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement(using: &myGenerator)!
// randomName == "Amani"
  • Parameter generator: The random number generator to use when choosing a random element.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Note: The algorithm used to select a random element may change in a future version of Swift. If you're passing a generator that results in the same sequence of elements each time you run your program, that sequence may change when your program is compiled using a different version of Swift.

Declaration

@inlinable public func randomElement<T>(using generator: inout T) -> Self.Element? where T: RandomNumberGenerator
func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [Self.SubSequence]

Returns the longest possible subsequences of the collection, in order, that don't contain elements satisfying the given predicate.

The resulting array consists of at most maxSplits + 1 subsequences. Elements that are used to split the sequence are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string using a closure that matches spaces. The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

print(line.split(maxSplits: 1, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

The final example passes false for the omittingEmptySubsequences parameter, so the returned array contains empty strings where spaces were repeated.

print(line.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [Self.SubSequence]
subscript subscript(r:)

Accesses the contiguous subrange of the collection's elements specified by a range expression.

The range expression is converted to a concrete subrange relative to this collection. For example, using a PartialRangeFrom range expression with an array accesses the subrange from the start of the range expression until the end of the array.

let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2...]
print(streetsSlice)
// ["Channing", "Douglas", "Evarts"]

The accessed slice uses the same indices for the same elements as the original collection uses. This example searches streetsSlice for one of the strings in the slice, and then uses that index in the original array.

let index = streetsSlice.firstIndex(of: "Evarts")    // 4
print(streets[index!])
// "Evarts"

Always use the slice's startIndex property instead of assuming that its indices start at a particular value. Attempting to access an element by using an index outside the bounds of the slice's indices may result in a runtime error, even if that index is valid for the original collection.

print(streetsSlice.startIndex)
// 2
print(streetsSlice[2])
// "Channing"

print(streetsSlice[0])
// error: Index out of bounds
  • Parameter bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Complexity: O(1)

Declaration

@inlinable public subscript<R>(r: R) where R: RangeExpression, Self.Index == R.Bound -> Self.SubSequence
subscript subscript(x:)

Declaration

@inlinable public subscript(x: (UnboundedRange_) -> ()) -> Self.SubSequence
func suffix(_ maxLength: Int) -> Self.SubSequence

Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

@inlinable public func suffix(_ maxLength: Int) -> Self.SubSequence
func suffix(from start: Self.Index) -> Self.SubSequence

Returns a subsequence from the specified position to the end of the collection.

The following example searches for the index of the number 40 in an array of integers, and then prints the suffix of the array starting at that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.suffix(from: i))
}
// Prints "[40, 50, 60]"

Passing the collection's endIndex as the start parameter results in an empty subsequence.

print(numbers.suffix(from: numbers.endIndex))
// Prints "[]"

Using the suffix(from:) method is equivalent to using a partial range from the index as the collection's subscript. The subscript notation is preferred over suffix(from:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[i...])
}
// Prints "[40, 50, 60]"
  • Parameter start: The index at which to start the resulting subsequence. start must be a valid index of the collection.

Complexity: O(1)

Declaration

@inlinable public func suffix(from start: Self.Index) -> Self.SubSequence
var underestimatedCount

A value less than or equal to the number of elements in the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

var underestimatedCount: Int