Display

Swift Version

Array

struct Array<Element>

An ordered, random-access collection.

Arrays are one of the most commonly used data types in an app. You use
arrays to organize your app's data. Specifically, you use the Array type
to hold elements of a single type, the array's Element type. An array
can store any kind of elements---from integers to strings to classes.

Swift makes it easy to create arrays in your code using an array literal:
simply surround a comma separated list of values with square brackets.
Without any other information, Swift creates an array that includes the
specified values, automatically inferring the array's Element type. For
example:

You can access individual array elements through a subscript. The first
element of a nonempty array is always at index zero. You can subscript an
array with any integer from zero up to, but not including, the count of
the array. Using a negative number or an index equal to or greater than
count triggers a runtime error. For example:

See the Sequence, Collection, and RangeReplaceableCollection
protocols for more methods available to arrays.

Adding and Removing Elements

Suppose you need to store a list of the names of students that are signed
up for a class you're teaching. During the registration period, you need
to add and remove names as students add and drop the class.

var students = ["Ben", "Ivy", "Jordell"]

To add single elements to the end of an array, use the append(_:) method.
Add multiple elements at the same time by passing another array or a
sequence of any kind to the append(contentsOf:) method.

You can add new elements in the middle of an array by using the
insert(_:at:) method for single elements and by using
insert(contentsOf:at:) to insert multiple elements from another
collection or array literal. The elements at that index and later indices
are shifted back to make room.

To remove elements from an array, use the remove(at:),
removeSubrange(_:), and removeLast() methods.

// Ben's family is moving to another state
students.remove(at: 0)
// ["Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"]
// William is signing up for a different class
students.removeLast()
// ["Ivy", "Jordell", "Liam", "Maxime", "Shakia"]

You can replace an existing element with a new value by assigning the new
value to the subscript.

Growing the Size of an Array

Every array reserves a specific amount of memory to hold its contents. When
you add elements to an array and that array begins to exceed its reserved
capacity, the array allocates a larger region of memory and copies its
elements into the new storage. The new storage is a multiple of the old
storage's size. This exponential growth strategy means that appending an
element happens in constant time, averaging the performance of many append
operations. Append operations that trigger reallocation have a performance
cost, but they occur less and less often as the array grows larger.

If you know approximately how many elements you will need to store, use the
reserveCapacity(_:) method before appending to the array to avoid
intermediate reallocations. Use the capacity and count properties to
determine how many more elements the array can store without allocating
larger storage.

For arrays of most Element types, this storage is a contiguous block of
memory. For arrays with an Element type that is a class or @objc
protocol type, this storage can be a contiguous block of memory or an
instance of NSArray. Because any arbitrary subclass of NSArray can
become an Array, there are no guarantees about representation or
efficiency in this case.

Modifying Copies of Arrays

Each array has an independent value that includes the values of all of its
elements. For simple types such as integers and other structures, this
means that when you change a value in one array, the value of that element
does not change in any copies of the array. For example:

If the elements in an array are instances of a class, the semantics are the
same, though they might appear different at first. In this case, the
values stored in the array are references to objects that live outside the
array. If you change a reference to an object in one array, only that
array has a reference to the new object. However, if two arrays contain
references to the same object, you can observe changes to that object's
properties from both arrays. For example:

Arrays, like all variable-size collections in the standard library, use
copy-on-write optimization. Multiple copies of an array share the same
storage until you modify one of the copies. When that happens, the array
being modified replaces its storage with a uniquely owned copy of itself,
which is then modified in place. Optimizations are sometimes applied that
can reduce the amount of copying.

This means that if an array is sharing storage with other copies, the first
mutating operation on that array incurs the cost of copying the array. An
array that is the sole owner of its storage can perform mutating
operations in place.

In the example below, a numbers array is created along with two copies
that share the same storage. When the original numbers array is
modified, it makes a unique copy of its storage before making the
modification. Further modifications to numbers are made in place, while
the two copies continue to share the original storage.

Bridging Between Array and NSArray

When you need to access APIs that expect data in an NSArray instance
instead of Array, use the type-cast operator (as) to bridge your
instance. For bridging to be possible, the Element type of your array
must be a class, an @objc protocol (a protocol imported from Objective-C
or marked with the @objc attribute), or a type that bridges to a
Foundation type.

The following example shows how you can bridge an Array instance to
NSArray to use the write(to:atomically:) method. In this example, the
colors array can be bridged to NSArray because its String elements
bridge to NSString. The compiler prevents bridging the moreColors
array, on the other hand, because its Element type is
Optional<String>, which does not bridge to a Foundation type.

Bridging from Array to NSArray takes O(1) time and O(1) space if the
array's elements are already instances of a class or an @objc protocol;
otherwise, it takes O(n) time and space.

Bridging from NSArray to Array first calls the copy(with:)
(**copyWithZone:** in Objective-C) method on the array to get an immutable
copy and then performs additional Swift bookkeeping work that takes O(1)
time. For instances of NSArray that are already immutable, copy(with:)
usually returns the same array in O(1) time; otherwise, the copying
performance is unspecified. The instances of NSArray and Array share
storage using the same copy-on-write optimization that is used when two
instances of Array share storage.

Note: The ContiguousArray and ArraySlice types are not bridged;
instances of those types always have a contiguous block of memory as
their storage.
See Also:ContiguousArray, ArraySlice, Sequence, Collection,
RangeReplaceableCollection

Declaration

You can use this initializer to create an array from any other type that
conforms to the Sequence protocol. For example, you might want to
create an array with the integers from 1 through 7. Use this initializer
around a range instead of typing all those numbers in an array literal.

You can also use this initializer to convert a complex sequence or
collection type back to an array. For example, the keys property of
a dictionary isn't an array with its own storage, it's a collection
that maps its elements from the dictionary only when they're
accessed, saving the time and space needed to allocate an array. If
you need to pass those keys to a method that takes an array, however,
use this initializer to convert that list from its type of
LazyMapCollection<Dictionary<String, Int>, Int> to a simple
[String].

Declaration

Declared In

Do not call this initializer directly. It is used by the compiler
when you use an array literal. Instead, create a new array by using an
array literal as its value. To do this, enclose a comma-separated list of
values in square brackets.

Here, an array of strings is created from an array literal holding
only strings.

Declaration

Declared In

Instance Variables

The total number of elements that the array can contain using its current
storage.

If the array grows larger than its capacity, it discards its current
storage and allocates a larger one.

The following example creates an array of integers from an array literal,
then appends the elements of another collection. Before appending, the
array allocates new storage that is large enough store the resulting
elements.

Declaration

Declaration

The array's "past the end" position---that is, the position one greater
than the last valid subscript argument.

When you need a range that includes the last element of an array, use the
half-open range operator (..<) with endIndex. The ..< operator
creates a range that doesn't include the upper bound, so it's always
safe to use with endIndex. For example:

Declaration

Declared In

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.

Declaration

Declared In

The following example uses indexed subscripting to update an array's
second element. After assigning the new value ("Butler") at a specific
position, that value is immediately available at that same position.

index: The position of the element to access. index must be
greater than or equal to startIndex and less than endIndex.

Complexity: Reading an element from an array is O(1). Writing is O(1)
unless the array's storage is shared with another array, in which case
writing is O(n), where n is the length of the array.
If the array uses a bridged NSArray instance as its storage, the
efficiency is unspecified.

Declaration

The returned ArraySlice instance uses the same indices for the same
elements as the original array. In particular, that slice, unlike an
array, may have a nonzero startIndex and an endIndex that is not
equal to count. Always use the slice's startIndex and endIndex
properties instead of assuming that its indices start or end 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.

Because arrays increase their allocated capacity using an exponential
strategy, appending a single element to an array is an O(1) operation
when averaged over many calls to the append(_:) method. When an array
has additional capacity and is not sharing its storage with another
instance, appending an element is O(1). When an array needs to
reallocate storage before appending or its storage is shared with
another copy, appending is O(n), where n is the length of the array.

newElement: The element to append to the array.

Complexity: Amortized O(1) over many additions. If the array uses a
bridged NSArray instance as its storage, the efficiency is
unspecified.

predicate: A closure that takes an element of the sequence
as its argument and returns a Boolean value that indicates whether
the passed element represents a match.
Returns:true if the sequence contains an element that satisfies
predicate; otherwise, false.

Declaration

Declared In

Returns a Boolean value indicating whether this sequence and another
sequence contain equivalent elements, using the given predicate as the
equivalence test.

At least one of the sequences must be finite.

The predicate must be a equivalence relation over the elements. That
is, for any elements a, b, and c, the following conditions must
hold:

areEquivalent(a, a) is always true. (Reflexivity)

areEquivalent(a, b) implies areEquivalent(b, a). (Symmetry)

If areEquivalent(a, b) and areEquivalent(b, c) are both true, then
areEquivalent(a, c) is also true. (Transitivity)

Parameters:other: A sequence to compare to this sequence.
areEquivalent: A predicate that returns true if its two arguments
are equivalent; otherwise, false.
Returns:true if this sequence and other contain equivalent items,
using areEquivalent as the equivalence test; otherwise, false.

When enumerating a collection, the integer part of each pair is a counter
for the enumeration, not necessarily the index of the paired value.
These counters can only be used as indices in instances of zero-based,
integer-indexed collections, such as Array and ContiguousArray. For
other collections the counters may be out of range or of the wrong type
to use as an index. To iterate over the elements of a collection with its
indices, use the zip(_:_:) function.

This example iterates over the indices and elements of a set, building a
list of indices of names with five or fewer letters.

shouldInclude: A closure that takes an element of the
sequence as its argument and returns a Boolean value indicating
whether the element should be included in the returned array.
Returns: An array of the elements that includeElement allowed.

transform: A closure that accepts an element of this
sequence as its argument and returns an optional value.
Returns: An array of the non-nil results of calling transform
with each element of the sequence.

Complexity: O(m + n), where m is the length of this sequence
and n is the length of the result.

Declaration

Declared In

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

The value passed as n must not offset i beyond the endIndex or
before the startIndex of this collection, unless the index passed as
limit prevents offsetting beyond those bounds.

Parameters:i: A valid index of the collection.
n: The distance to offset i. n must not be negative unless the
collection conforms to the BidirectionalCollection protocol.
Returns:true if i has been offset by exactly n steps without
going beyond limit; otherwise, false. When the return value is
false, the value of i is equal to limit.

See Also:index(_:offsetBy:), formIndex(_:offsetBy:limitedBy:)Complexity: O(1) if the collection conforms to
RandomAccessCollection; otherwise, O(n), where n is the absolute
value of n.

Advancing an index beyond a collection's ending index or offsetting it
before a collection's starting index may trigger a runtime error. The
value passed as n must not result in such an operation.

Parameters:i: A valid index of the array.
n: The distance to offset i.
Returns: An index offset by n from the index i. If n is positive,
this is the same value as the result of n calls to index(after:).
If n is negative, this is the same value as the result of -n calls
to index(before:).

Complexity: O(1)

Declaration

func index(_ i: Int, offsetBy n: Int) -> Int

Declared In

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 an
array's starting index and then prints the element at that position. The
operation doesn't require going beyond the limiting numbers.endIndex
value, so it succeeds.

Advancing an index beyond a collection's ending index or offsetting it
before a collection's starting index may trigger a runtime error. The
value passed as n must not result in such an operation.

Parameters:i: A valid index of the array.
n: The distance to offset i.
limit: A valid index of the collection to use as a limit. If n > 0,
limit has no effect if it is less than i. Likewise, if n < 0,
limit has no effect if it is greater than i.
Returns: An index offset by n from the index i, unless that index
would be beyond limit in the direction of movement. In that case,
the method returns nil.

Declaration

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

predicate: A closure that takes an element as its argument
and returns a Boolean value that indicates whether the passed element
represents a match.
Returns: The index of the first element for which predicate returns
true. If no elements in the collection satisfy the given predicate,
returns nil.

Declaration

Declared In

Returns a Boolean value indicating whether the sequence precedes another
sequence in a lexicographical (dictionary) ordering, using the given
predicate to compare elements.

The predicate must be a strict weak ordering over the elements. That
is, for any elements a, b, and c, the following conditions must
hold:

areInIncreasingOrder(a, a) is always false. (Irreflexivity)

If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are
both true, then areInIncreasingOrder(a, c) is also
true. (Transitive comparability)

Two elements are incomparable if neither is ordered before the other
according to the predicate. If a and b are incomparable, and b
and c are incomparable, then a and c are also incomparable.
(Transitive incomparability)

Parameters:other: A sequence to compare to this sequence.
areInIncreasingOrder: A predicate that returns true if its first
argument should be ordered before its second argument; otherwise,
false.
Returns:true if this sequence precedes other in a dictionary
ordering as ordered by areInIncreasingOrder; otherwise, false.

Note: This method implements the mathematical notion of lexicographical
ordering, which has no connection to Unicode. If you are sorting
strings to present to the end user, use String APIs that perform
localized comparison instead.
See Also:lexicographicallyPrecedes(_:)

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.
Returns: An array containing the transformed elements of this
sequence.

Declaration

Declared In

Returns the maximum element in the sequence, using the given predicate
as the comparison between elements.

The predicate must be a strict weak ordering over the elements. That
is, for any elements a, b, and c, the following conditions must
hold:

areInIncreasingOrder(a, a) is always false. (Irreflexivity)

If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are
both true, then areInIncreasingOrder(a, c) is also
true. (Transitive comparability)

Two elements are incomparable if neither is ordered before the other
according to the predicate. If a and b are incomparable, and b
and c are incomparable, then a and c are also incomparable.
(Transitive incomparability)

This example shows how to use the max(by:) method on a
dictionary to find the key-value pair with the highest value.

areInIncreasingOrder: A predicate that returns true if its
first argument should be ordered before its second argument;
otherwise, false.
Returns: The sequence's maximum element if the sequence is not empty;
otherwise, nil.

Declaration

Declared In

Returns the minimum element in the sequence, using the given predicate as
the comparison between elements.

The predicate must be a strict weak ordering over the elements. That
is, for any elements a, b, and c, the following conditions must
hold:

areInIncreasingOrder(a, a) is always false. (Irreflexivity)

If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are
both true, then areInIncreasingOrder(a, c) is also
true. (Transitive comparability)

Two elements are incomparable if neither is ordered before the other
according to the predicate. If a and b are incomparable, and b
and c are incomparable, then a and c are also incomparable.
(Transitive incomparability)

This example shows how to use the min(by:) method on a
dictionary to find the key-value pair with the lowest value.

areInIncreasingOrder: A predicate that returns true
if its first argument should be ordered before its second
argument; otherwise, false.
Returns: The sequence's minimum element, according to
areInIncreasingOrder. If the sequence has no elements, returns
nil.

The numbers array is now arranged in two partitions. The first
partition, numbers.prefix(upTo: p), is made up of the elements that
are not greater than 30. The second partition, numbers.suffix(from: p),
is made up of the elements that are greater than 30.

belongsInSecondPartition: A predicate used to partition
the collection. All elements satisfying this predicate are ordered
after all elements not satisfying it.
Returns: The index of the first element in the reordered collection
that matches belongsInSecondPartition. If no elements in the
collection match belongsInSecondPartition, the returned index is
equal to the collection's endIndex.

maxLength: The maximum number of elements to return.
maxLength must be greater than or equal to zero.
Returns: A subsequence starting at the beginning of this collection
with at most maxLength elements.

Declaration

func prefix(_ maxLength: Int) -> ArraySlice<Element>

Declared In

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:

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.
Returns: A subsequence up to, and including, the end position.

Complexity: O(1)
See Also:prefix(upTo:)

Declaration

func prefix(through position: Int) -> ArraySlice<Element>

Declared In

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:

Declaration

Declared In

Returns the result of calling the given combining closure with each
element of this sequence and an accumulating value.

The nextPartialResult closure is called sequentially with an
accumulating value initialized to initialResult and each
element of the sequence. This example shows how to find the sum
of an array of numbers.

The nextPartialResult closure is called with the initial
result and the first element of numbers, returning the sum:
1.

The closure is called again repeatedly with the previous call's
return value and each element of the sequence.

When the sequence is exhausted, the last value returned from the
closure is returned to the caller.

Parameters:initialResult: the initial accumulating value.
nextPartialResult: A closure that combines an accumulating
value and an element of the sequence into a new accumulating
value, to be used in the next call of the
nextPartialResult closure or returned to the caller.
Returns: The final accumulated value.

Declaration

Declared In

Replaces a range of elements with the elements in the specified
collection.

This method has the effect of removing the specified range of elements
from the array and inserting the new elements at the same location. The
number of new elements need not match the number of elements being
removed.

In this example, three elements in the middle of an array of integers are
replaced by the five elements of a Repeated<Int> instance.

If you pass a zero-length range as the subrange parameter, this method
inserts the elements of newElements at subrange.startIndex. Calling
the insert(contentsOf:at:) method instead is preferred.

Likewise, if you pass a zero-length collection as the newElements
parameter, this method removes the elements in the given subrange
without replacement. Calling the removeSubrange(_:) method instead is
preferred.

Parameters:subrange: The subrange of the array to replace. The start and end of
a subrange must be valid indices of the array.
newElements: The new elements to add to the array.

Complexity: O(subrange.count) if you are replacing a suffix of the
array with an empty collection; otherwise, O(n), where n is the
length of the array.

Declared In

If you are adding a known number of elements to an array, use this method
to avoid multiple reallocations. This method ensures that the array has
unique, mutable, contiguous storage, with space allocated for at least
the requested number of elements.

For performance reasons, the newly allocated storage may be larger than
the requested capacity. Use the array's capacity property to determine
the size of the new storage.

Declaration

Declared In

Returns a view presenting the elements of the collection in reverse
order.

You can reverse a collection without allocating new space for its
elements by calling this reversed() method. A
ReversedRandomAccessCollection instance wraps an underlying collection
and provides access to its elements in reverse order. This example
prints the elements of an array in reverse order:

If you need a reversed collection of the same type, you may be able to
use the collection's sequence-based or collection-based initializer. For
example, to get the reversed version of an array, initialize a new
Array instance from the result of this reversed() method.

Declaration

Declared In

Sorts the collection in place, using the given predicate as the
comparison between elements.

When you want to sort a collection of elements that doesn't conform to
the Comparable protocol, pass a closure to this method that returns
true when the first element passed should be ordered before the
second.

The predicate must be a strict weak ordering over the elements. That
is, for any elements a, b, and c, the following conditions must
hold:

areInIncreasingOrder(a, a) is always false. (Irreflexivity)

If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are
both true, then areInIncreasingOrder(a, c) is also true.
(Transitive comparability)

Two elements are incomparable if neither is ordered before the other
according to the predicate. If a and b are incomparable, and b
and c are incomparable, then a and c are also incomparable.
(Transitive incomparability)

The sorting algorithm is not stable. A nonstable sort may change the
relative order of elements for which areInIncreasingOrder does not
establish an order.

In the following example, the closure provides an ordering for an array
of a custom enumeration that describes an HTTP response. The predicate
orders errors before successes and sorts the error responses by their
error code.

Alternatively, use this method to sort a collection of elements that do
conform to Comparable when you want the sort to be descending instead
of ascending. Pass the greater-than operator (>) operator as the
predicate.

Declaration

Declared In

Returns the elements of the collection, sorted using the given
predicate as the comparison between elements.

When you want to sort a collection of elements that don't conform to
the Comparable protocol, pass a predicate to this method that returns
true when the first element passed should be ordered before the
second. The elements of the resulting array are ordered according to the
given predicate.

The predicate must be a strict weak ordering over the elements. That
is, for any elements a, b, and c, the following conditions must
hold:

areInIncreasingOrder(a, a) is always false. (Irreflexivity)

If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are
both true, then areInIncreasingOrder(a, c) is also true.
(Transitive comparability)

Two elements are incomparable if neither is ordered before the other
according to the predicate. If a and b are incomparable, and b
and c are incomparable, then a and c are also incomparable.
(Transitive incomparability)

The sorting algorithm is not stable. A nonstable sort may change the
relative order of elements for which areInIncreasingOrder does not
establish an order.

In the following example, the predicate provides an ordering for an array
of a custom HTTPResponse type. The predicate orders errors before
successes and sorts the error responses by their error code.

You also use this method to sort elements that conform to the
Comparable protocol in descending order. To sort your collection
in descending order, pass the greater-than operator (>) as the
areInIncreasingOrder parameter.

Declaration

Declared In

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.

Parameters:maxSplits: The maximum number of times to split the collection, or
one less than the number of subsequences to return. If
maxSplits + 1 subsequences are returned, the last one is a suffix
of the original collection containing the remaining elements.
maxSplits must be greater than or equal to zero. The default value
is Int.max.
omittingEmptySubsequences: If false, an empty subsequence is
returned in the result for each pair of consecutive elements
satisfying the isSeparator predicate and for each element at the
start or end of the collection satisfying the isSeparator
predicate. The default value is true.
isSeparator: A closure that takes an element as an argument and
returns a Boolean value indicating whether the collection should be
split at that element.
Returns: An array of subsequences, split from this collection's
elements.

Declared In

Returns a Boolean value indicating whether the initial elements of the
sequence are equivalent to the elements in another sequence, using
the given predicate as the equivalence test.

The predicate must be a equivalence relation over the elements. That
is, for any elements a, b, and c, the following conditions must
hold:

areEquivalent(a, a) is always true. (Reflexivity)

areEquivalent(a, b) implies areEquivalent(b, a). (Symmetry)

If areEquivalent(a, b) and areEquivalent(b, c) are both true, then
areEquivalent(a, c) is also true. (Transitivity)

Parameters:possiblePrefix: A sequence to compare to this sequence.
areEquivalent: A predicate that returns true if its two arguments
are equivalent; otherwise, false.
Returns:true if the initial elements of the sequence are equivalent
to the elements of possiblePrefix; otherwise, false. If
possiblePrefix has no elements, the return value is true.

Declaration

Declared In

Calls a closure with a pointer to the array's contiguous storage.
If no such storage exists, it is first created.

Often, the optimizer can eliminate bounds checks within an array
algorithm, but when that fails, invoking the same algorithm on the
buffer pointer passed into your closure lets you trade safety for speed.

The following example shows how you can iterate over the contents of the
buffer pointer:

body: A closure with an UnsafeBufferPointer parameter that
points to the contiguous storage for the array. If body has a return
value, it is used as the return value for the
withUnsafeBufferPointer(_:) method. The pointer argument is valid
only for the duration of the closure's execution.
Returns: The return value of the body closure parameter, if any.

body: A closure with an UnsafeRawBufferPointer parameter
that points to the contiguous storage for the array. If body has a
return value, it is used as the return value for the
withUnsafeBytes(_:) method. The argument is valid only for the
duration of the closure's execution.
Returns: The return value of the body closure parameter, if any.

Declaration

Calls the given closure with a pointer to the array's mutable contiguous
storage. If no such storage exists, it is first created.

Often, the optimizer can eliminate bounds checks within an array
algorithm, but when that fails, invoking the same algorithm on the
buffer pointer passed into your closure lets you trade safety for speed.

The following example shows modifying the contents of the
UnsafeMutableBufferPointer argument to body alters the contents of
the array:

Warning: Do not rely on anything about self (the array that is the
target of this method) during the execution of the body closure: It
may not appear to have its correct value. Instead, use only the
UnsafeMutableBufferPointer argument to body.

body: A closure with an UnsafeMutableBufferPointer
parameter that points to the contiguous storage for the array. If
body has a return value, it is used as the return value for the
withUnsafeMutableBufferPointer(_:) method. The pointer argument is
valid only for the duration of the closure's execution.
Returns: The return value of the body closure parameter, if any.

body: A closure with an UnsafeRawBufferPointer
parameter that points to the contiguous storage for the array. If body
has a return value, it is used as the return value for the
withUnsafeMutableBytes(_:) method. The argument is valid only for the
duration of the closure's execution.
Returns: The return value of the body closure parameter, if any.

See Also:withUnsafeBytes, UnsafeMutableRawBufferPointer

Declaration

Conditionally Inherited Items

The initializers, methods, and properties listed below may be available on this type under certain conditions (such as methods that are available on Array when its elements are Equatable) or may not ever be available if that determination is beyond SwiftDoc.org's capabilities. Please open an issue on GitHub if you see something out of place!

Declared In

Replaces the specified subrange of elements with the given collection.

This method has the effect of removing the specified range of elements
from the collection and inserting the new elements at the same location.
The number of new elements need not match the number of elements being
removed.

In this example, three elements in the middle of an array of integers are
replaced by the five elements of a Repeated<Int> instance.

If you pass a zero-length range as the subrange parameter, this method
inserts the elements of newElements at subrange.startIndex. Calling
the insert(contentsOf:at:) method instead is preferred.

Likewise, if you pass a zero-length collection as the newElements
parameter, this method removes the elements in the given subrange
without replacement. Calling the removeSubrange(_:) method instead is
preferred.

Calling this method may invalidate any existing indices for use with this
collection.

Parameters:subrange: The subrange of the collection to replace. The bounds of
the range must be valid indices of the collection.
newElements: The new elements to add to the collection.

Complexity: O(m), where m is the combined length of the collection
and newElements. If the call to replaceSubrange simply appends the
contents of newElements to the collection, the complexity is O(n),
where n is the length of newElements.

Declared In

Replaces the specified subrange of elements with the given collection.

This method has the effect of removing the specified range of elements
from the collection and inserting the new elements at the same location.
The number of new elements need not match the number of elements being
removed.

In this example, three elements in the middle of an array of integers are
replaced by the five elements of a Repeated<Int> instance.

If you pass a zero-length range as the subrange parameter, this method
inserts the elements of newElements at subrange.startIndex. Calling
the insert(contentsOf:at:) method instead is preferred.

Likewise, if you pass a zero-length collection as the newElements
parameter, this method removes the elements in the given subrange
without replacement. Calling the removeSubrange(_:) method instead is
preferred.

Calling this method may invalidate any existing indices for use with this
collection.

Parameters:subrange: The subrange of the collection to replace. The bounds of
the range must be valid indices of the collection.
newElements: The new elements to add to the collection.

Complexity: O(m), where m is the combined length of the collection
and newElements. If the call to replaceSubrange simply appends the
contents of newElements to the collection, the complexity is O(n),
where n is the length of newElements.

Declared In

The indices that are valid for subscripting the collection, in ascending
order.

A collection's indices property can hold a strong reference to the
collection itself, causing the collection to be non-uniquely referenced.
If you mutate the collection while iterating over its indices, a strong
reference can cause an unexpected copy of the collection. To avoid the
unexpected copy, use the index(after:) method starting with
startIndex to produce indices instead.

The value passed as n must not offset i beyond the endIndex or
before the startIndex of this collection.

Parameters:i: A valid index of the collection.
n: The distance to offset i.
Returns: An index offset by n from the index i. If n is positive,
this is the same value as the result of n calls to index(after:).
If n is negative, this is the same value as the result of -n calls
to index(before:).

Declaration

Declared In

Where Indices == DefaultBidirectionalIndices

The indices that are valid for subscripting the collection, in ascending
order.

A collection's indices property can hold a strong reference to the
collection itself, causing the collection to be non-uniquely referenced.
If you mutate the collection while iterating over its indices, a strong
reference can cause an unexpected copy of the collection. To avoid the
unexpected copy, use the index(after:) method starting with
startIndex to produce indices instead.

Declaration

Declared In

Where Indices == DefaultIndices

The indices that are valid for subscripting the collection, in ascending
order.

A collection's indices property can hold a strong reference to the
collection itself, causing the collection to be non-uniquely referenced.
If you mutate the collection while iterating over its indices, a strong
reference can cause an unexpected copy of the collection. To avoid the
unexpected copy, use the index(after:) method starting with
startIndex to produce indices instead.

Declaration

Declared In

Where Indices == DefaultRandomAccessIndices

The indices that are valid for subscripting the collection, in ascending
order.

A collection's indices property can hold a strong reference to the
collection itself, causing the collection to be non-uniquely referenced.
If you mutate the collection while iterating over its indices, a strong
reference can cause an unexpected copy of the collection. To avoid the
unexpected copy, use the index(after:) method starting with
startIndex to produce indices instead.

other: A sequence to compare to this sequence.
Returns:true if this sequence precedes other in a dictionary
ordering; otherwise, false.

Note: This method implements the mathematical notion of lexicographical
ordering, which has no connection to Unicode. If you are sorting
strings to present to the end user, use String APIs that
perform localized comparison.
See Also:lexicographicallyPrecedes(_:by:)

Declaration

Declared In

Returns the first index where the specified value appears in the
collection.

After using index(of:) to find the position of a particular element in
a collection, you can use it to access the element by subscripting. This
example shows how you can modify one of the names in an array of
students.

Declaration

Declared In

Returns the longest possible subsequences of the collection, in order,
around elements equal to the given element.

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

The following examples show the effects of the maxSplits and
omittingEmptySubsequences parameters when splitting a string at each
space character (" "). The first use of split returns each word that
was originally separated by one or more spaces.

Parameters:separator: The element that should be split upon.
maxSplits: The maximum number of times to split the collection, or
one less than the number of subsequences to return. If
maxSplits + 1 subsequences are returned, the last one is a suffix
of the original collection containing the remaining elements.
maxSplits must be greater than or equal to zero. The default value
is Int.max.
omittingEmptySubsequences: If false, an empty subsequence is
returned in the result for each consecutive pair of separator
elements in the collection and for each instance of separator at
the start or end of the collection. If true, only nonempty
subsequences are returned. The default value is true.
Returns: An array of subsequences, split from this collection's
elements.

Passing an sequence with no elements or an empty collection as
possiblePrefix always results in true.

print(b.starts(with: []))
// Prints "true"

possiblePrefix: A sequence to compare to this sequence.
Returns:true if the initial elements of the sequence are the same as
the elements of possiblePrefix; otherwise, false. If
possiblePrefix has no elements, the return value is true.