struct
ContiguousArray
A contiguously stored array.
Inheritance | CustomDebugStringConvertible, CustomReflectable, CustomStringConvertible, ExpressibleByArrayLiteral, MutableCollection, RandomAccessCollection, RangeReplaceableCollection |
---|---|
Associated Types |
|
Initializers
Creates a new instance of a collection containing the elements of a sequence.
- Parameter elements: The sequence of elements for the new collection.
Declaration
@
inlinable
public
init
<
S
>
(
_
elements
:
S
)
where
S
:
Sequence
,
Self
.
Element
==
S
.
Element
Creates an array containing the elements of a sequence.
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.
let
numbers
=
Array
(
1
...
7
)
(
numbers
)
// Prints "[1, 2, 3, 4, 5, 6, 7]"
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]
.
func
cacheImagesWithNames
(
names
: [
String
]) {
// custom image loading and caching
}
let
namedHues
: [
String
:
Int
] = [
"Vermillion"
:
18
,
"Magenta"
:
302
,
"Gold"
:
50
,
"Cerise"
:
320
]
let
colorNames
=
Array
(
namedHues
.
keys
)
cacheImagesWithNames
(
colorNames
)
(
colorNames
)
// Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"
- Parameter s: The sequence of elements to turn into an array.
Declaration
@
inlinable
public
init
<
S
>
(
_
s
:
S
)
where
Element
==
S
.
Element
,
S
:
Sequence
Creates an array from the given array literal.
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:
let
ingredients
:
ContiguousArray
=
[
"cocoa beans"
,
"sugar"
,
"cocoa butter"
,
"salt"
]
- Parameter elements: A variadic list of elements of the new array.
Declaration
@
inlinable
public
init
(
arrayLiteral
elements
:
Element
)
Creates a new collection containing the specified number of a single, repeated value.
Here's an example of creating an array initialized with five strings containing the letter Z.
let
fiveZs
=
Array
(
repeating
:
"Z"
,
count
:
5
)
(
fiveZs
)
// Prints "["Z", "Z", "Z", "Z", "Z"]"
Declaration
@
inlinable
public
init
(
repeating
repeatedValue
:
Self
.
Element
,
count
:
Int
)
Creates a new array containing the specified number of a single, repeated value.
Here's an example of creating an array initialized with five strings containing the letter Z.
let
fiveZs
=
Array
(
repeating
:
"Z"
,
count
:
5
)
(
fiveZs
)
// Prints "["Z", "Z", "Z", "Z", "Z"]"
Declaration
@
inlinable
public
init
(
repeating
repeatedValue
:
Element
,
count
:
Int
)
Creates an array with the specified capacity, then calls the given closure with a buffer covering the array's uninitialized memory.
Inside the closure, set the initializedCount
parameter to the number of
elements that are initialized by the closure. The memory in the range
buffer[0..<initializedCount]
must be initialized at the end of the
closure's execution, and the memory in the range
buffer[initializedCount...]
must be uninitialized. This postcondition
must hold even if the initializer
closure throws an error.
Note: While the resulting array may have a capacity larger than the requested amount, the buffer passed to the closure will cover exactly the requested number of elements.
Declaration
@
inlinable
public
init
(
unsafeUninitializedCapacity
:
Int
,
initializingWith
initializer
: (
inout
UnsafeMutableBufferPointer
<
Element
>
,
inout
Int
)
throws
-
>
Void
)
rethrows
Instance Variables
The total number of elements that the array can contain without allocating new storage.
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.
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.
var
numbers
= [
10
,
20
,
30
,
40
,
50
]
// numbers.count == 5
// numbers.capacity == 5
numbers
.
append
(
contentsOf
:
stride
(
from
:
60
,
through
:
100
,
by
:
10
))
// numbers.count == 10
// numbers.capacity == 12
Declaration
var
capacity
:
Int
A textual representation of the array and its elements, suitable for debugging.
Declaration
var
debugDescription
:
String
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:
let
numbers
= [
10
,
20
,
30
,
40
,
50
]
if
let
i
=
numbers
.
firstIndex
(
of
:
30
) {
(
numbers
[
i
..
<
numbers
.
endIndex
])
}
// Prints "[30, 40, 50]"
If the array is empty, endIndex
is equal to startIndex
.
Declaration
var
endIndex
:
Int
The position of the first element in a nonempty array.
For an instance of ContiguousArray
, startIndex
is always zero. If the array
is empty, startIndex
is equal to endIndex
.
Declaration
var
startIndex
:
Int
Subscripts
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
]
(
streetsSlice
)
// Prints "["Channing", "Douglas", "Evarts"]"
let
index
=
streetsSlice
.
firstIndex
(
of
:
"Evarts"
)
// 4
streets
[
index
!] =
"Eustace"
(
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
Accesses a contiguous subrange of the array's elements.
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.
let
streets
= [
"Adams"
,
"Bryant"
,
"Channing"
,
"Douglas"
,
"Evarts"
]
let
streetsSlice
=
streets
[
2
..
<
streets
.
endIndex
]
(
streetsSlice
)
// Prints "["Channing", "Douglas", "Evarts"]"
let
i
=
streetsSlice
.
firstIndex
(
of
:
"Evarts"
)
// 4
(
streets
[
i
!])
// Prints "Evarts"
- Parameter bounds: A range of integers. The bounds of the range must be valid indices of the array.
Declaration
@
inlinable
public
subscript
(
bounds
:
Range
<
Int
>
) -
>
ArraySlice
<
Element
>
Accesses the element at the specified position.
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.
var
streets
= [
"Adams"
,
"Bryant"
,
"Channing"
,
"Douglas"
,
"Evarts"
]
streets
[
1
] =
"Butler"
(
streets
[
1
])
// Prints "Butler"
- Parameter index: The position of the element to access.
index
must be greater than or equal tostartIndex
and less thanendIndex
.
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.
Declaration
@
inlinable
public
subscript
(
index
:
Int
) -
>
Element
Declaration
@
inlinable
public
subscript
<
R
>
(
r
:
R
)
where
R
:
RangeExpression
,
Self
.
Index
==
R
.
Bound
-
>
Self
.
SubSequence
Declaration
@
inlinable
public
subscript
(
x
: (
UnboundedRange_
) -
>
()) -
>
Self
.
SubSequence
Instance Methods
Adds an element to the end of the collection.
If the collection does not have sufficient capacity for another element,
additional storage is allocated before appending newElement
. The
following example adds a new number to an array of integers:
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
append
(
100
)
(
numbers
)
// Prints "[1, 2, 3, 4, 5, 100]"
- Parameter newElement: The element to append to the collection.
Complexity: O(1) on average, over many calls to
append(_:)
on the same collection.
Declaration
@
inlinable
public
mutating
func
append
(
_
newElement
:
Self
.
Element
)
Adds a new element at the end of the array.
Use this method to append a single element to the end of a mutable array.
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
append
(
100
)
(
numbers
)
// Prints "[1, 2, 3, 4, 5, 100]"
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.
- Parameter newElement: The element to append to the array.
Complexity: O(1) on average, over many calls to
append(_:)
on the same array.
Declaration
@
inlinable
public
mutating
func
append
(
_
newElement
:
Element
)
Adds the elements of a sequence or collection to the end of this collection.
The collection being appended to allocates any additional necessary storage to hold the new elements.
The following example appends the elements of a Range<Int>
instance to
an array of integers:
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
append
(
contentsOf
:
10
...
15
)
(
numbers
)
// Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
- Parameter newElements: The elements to append to the collection.
Complexity: O(m), where m is the length of
newElements
.
Declaration
@
inlinable
public
mutating
func
append
<
S
>
(
contentsOf
newElements
:
S
)
where
S
:
Sequence
,
Self
.
Element
==
S
.
Element
Adds the elements of a sequence to the end of the array.
Use this method to append the elements of a sequence to the end of this
array. This example appends the elements of a Range<Int>
instance
to an array of integers.
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
append
(
contentsOf
:
10
...
15
)
(
numbers
)
// Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
- Parameter newElements: The elements to append to the array.
Complexity: O(m) on average, where m is the length of
newElements
, over many calls toappend(contentsOf:)
on the same array.
Declaration
@
inlinable
public
mutating
func
append
<
S
>
(
contentsOf
newElements
:
S
)
where
Element
==
S
.
Element
,
S
:
Sequence
Applies the given difference to this collection.
- Parameter difference: The difference to be applied.
Complexity: O(n + c), where n is
self.count
and c is the number of changes contained by the parameter.
Declaration
@
available
(
OSX
10.15
,
iOS
13
,
tvOS
13
,
watchOS
6
, *)
public
func
applying
(
_
difference
:
CollectionDifference
<
Self
.
Element
>
) -
>
Self
?
Returns a new collection of the same type containing, in order, the elements of the original collection that satisfy the given predicate.
In this example, filter(_:)
is used to include only names shorter than
five characters.
let
cast
= [
"Vivien"
,
"Marlon"
,
"Kim"
,
"Karl"
]
let
shortNames
=
cast
.
filter
{ $
0
.
count
<
5
}
(
shortNames
)
// Prints "["Kim", "Karl"]"
- Parameter isIncluded: 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 collection.
Complexity: O(n), where n is the length of the collection.
Declaration
@
available
(
swift
4.0
) @
inlinable
public
func
filter
(
_
isIncluded
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Self
Replaces the given index with its successor.
- Parameter i: A valid index of the collection.
i
must be less thanendIndex
.
Declaration
@
inlinable
public
func
formIndex
(
after
i
:
inout
Int
)
Replaces the given index with its predecessor.
- Parameter i: A valid index of the collection.
i
must be greater thanstartIndex
.
Declaration
@
inlinable
public
func
formIndex
(
before
i
:
inout
Int
)
Returns an index that is the specified distance from the given index.
The following example obtains an index advanced four positions from an array's starting index and then prints the element at that position.
let
numbers
= [
10
,
20
,
30
,
40
,
50
]
let
i
=
numbers
.
index
(
numbers
.
startIndex
,
offsetBy
:
4
)
(
numbers
[
i
])
// Prints "50"
The value passed as distance
must not offset i
beyond the bounds of
the collection.
Declaration
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.
let
numbers
= [
10
,
20
,
30
,
40
,
50
]
let
i
=
numbers
.
index
(
numbers
.
startIndex
,
offsetBy
:
4
)
(
numbers
[
i
])
// Prints "50"
The next example attempts to retrieve an index ten positions from
numbers.startIndex
, but fails, because that distance is beyond the
index passed as limit
.
let
j
=
numbers
.
index
(
numbers
.
startIndex
,
offsetBy
:
10
,
limitedBy
:
numbers
.
endIndex
)
(
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)
Declaration
@
inlinable
public
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 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.
let
numbers
= [
10
,
20
,
30
,
40
,
50
]
if
let
i
=
numbers
.
index
(
numbers
.
startIndex
,
offsetBy
:
4
,
limitedBy
:
numbers
.
endIndex
) {
(
numbers
[
i
])
}
// Prints "50"
The next example attempts to retrieve an index ten positions from
numbers.startIndex
, but fails, because that distance is beyond the
index passed as limit
.
let
j
=
numbers
.
index
(
numbers
.
startIndex
,
offsetBy
:
10
,
limitedBy
:
numbers
.
endIndex
)
(
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)
Declaration
Inserts a new element into the collection at the specified position.
The new element is inserted before the element currently at the
specified index. If you pass the collection's endIndex
property as
the index
parameter, the new element is appended to the
collection.
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
insert
(
100
,
at
:
3
)
numbers
.
insert
(
200
,
at
:
numbers
.
endIndex
)
(
numbers
)
// Prints "[1, 2, 3, 100, 4, 5, 200]"
Calling this method may invalidate any existing indices for use with this collection.
- Parameter newElement: The new element to insert into the collection.
- Parameter i: The position at which to insert the new element.
index
must be a valid index into the collection.
Complexity: O(n), where n is the length of the collection. If
i == endIndex
, this method is equivalent toappend(_:)
.
Declaration
@
inlinable
public
mutating
func
insert
(
_
newElement
:
Self
.
Element
,
at
i
:
Self
.
Index
)
Inserts a new element at the specified position.
The new element is inserted before the element currently at the specified
index. If you pass the array's endIndex
property as the index
parameter, the new element is appended to the array.
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
insert
(
100
,
at
:
3
)
numbers
.
insert
(
200
,
at
:
numbers
.
endIndex
)
(
numbers
)
// Prints "[1, 2, 3, 100, 4, 5, 200]"
- Parameter newElement: The new element to insert into the array.
- Parameter i: The position at which to insert the new element.
index
must be a valid index of the array or equal to itsendIndex
property.
Complexity: O(n), where n is the length of the array. If
i == endIndex
, this method is equivalent toappend(_:)
.
Declaration
@
inlinable
public
mutating
func
insert
(
_
newElement
:
Element
,
at
i
:
Int
)
Inserts the elements of a sequence into the collection at the specified position.
The new elements are inserted before the element currently at the
specified index. If you pass the collection's endIndex
property as the
index
parameter, the new elements are appended to the collection.
Here's an example of inserting a range of integers into an array of the same type:
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
insert
(
contentsOf
:
100
...
103
,
at
:
3
)
(
numbers
)
// Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"
Calling this method may invalidate any existing indices for use with this collection.
- Parameter newElements: The new elements to insert into the collection.
- Parameter i: The position at which to insert the new elements.
index
must be a valid index of the collection.
Complexity: O(n + m), where n is length of this collection and m is the length of
newElements
. Ifi == endIndex
, this method is equivalent toappend(contentsOf:)
.
Declaration
@
inlinable
public
mutating
func
insert
<
C
>
(
contentsOf
newElements
:
C
,
at
i
:
Self
.
Index
)
where
C
:
Collection
,
Self
.
Element
==
C
.
Element
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
@
inlinable
public
mutating
func
partition
(
by
belongsInSecondPartition
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
-
>
Self
.
Index
Removes and returns the element at the specified position.
All the elements following the specified position are moved to close the gap. This example removes the middle element from an array of measurements.
var
measurements
= [
1.2
,
1.5
,
2.9
,
1.2
,
1.6
]
let
removed
=
measurements
.
remove
(
at
:
2
)
(
measurements
)
// Prints "[1.2, 1.5, 1.2, 1.6]"
Calling this method may invalidate any existing indices for use with this collection.
- Parameter position: The position of the element to remove.
position
must be a valid index of the collection that is not equal to the collection's end index.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
mutating
func
remove
(
at
position
:
Self
.
Index
) -
>
Self
.
Element
Removes and returns the element at the specified position.
All the elements following the specified position are moved up to close the gap.
var
measurements
: [
Double
] = [
1.1
,
1.5
,
2.9
,
1.2
,
1.5
,
1.3
,
1.2
]
let
removed
=
measurements
.
remove
(
at
:
2
)
(
measurements
)
// Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]"
- Parameter index: The position of the element to remove.
index
must be a valid index of the array.
Complexity: O(n), where n is the length of the array.
Declaration
@
inlinable
public
mutating
func
remove
(
at
index
:
Int
) -
>
Element
Removes all elements from the collection.
Calling this method may invalidate any existing indices for use with this collection.
- Parameter keepCapacity: Pass
true
to request that the collection avoid releasing its storage. Retaining the collection's storage can be a useful optimization when you're planning to grow the collection again. The default value isfalse
.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
mutating
func
removeAll
(
keepingCapacity
keepCapacity
:
Bool
=
false
)
Removes all elements from the array.
- Parameter keepCapacity: Pass
true
to keep the existing capacity of the array after removing its elements. The default value isfalse
.
Complexity: O(n), where n is the length of the array.
Declaration
@
inlinable
public
mutating
func
removeAll
(
keepingCapacity
keepCapacity
:
Bool
=
false
)
Removes all the elements that satisfy the given predicate.
Use this method to remove every element in a collection that meets particular criteria. The order of the remaining elements is preserved. This example removes all the vowels from a string:
- Parameter shouldBeRemoved: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be removed from the collection.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
mutating
func
removeAll
(
where
shouldBeRemoved
: (
Self
.
Element
)
throws
-
>
Bool
)
rethrows
Removes and returns the first element of the collection.
The collection must not be empty.
var
bugs
= [
"Aphid"
,
"Bumblebee"
,
"Cicada"
,
"Damselfly"
,
"Earwig"
]
bugs
.
removeFirst
()
(
bugs
)
// Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]"
Calling this method may invalidate any existing indices for use with this collection.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
mutating
func
removeFirst
() -
>
Self
.
Element
Removes the specified number of elements from the beginning of the collection.
var
bugs
= [
"Aphid"
,
"Bumblebee"
,
"Cicada"
,
"Damselfly"
,
"Earwig"
]
bugs
.
removeFirst
(
3
)
(
bugs
)
// Prints "["Damselfly", "Earwig"]"
Calling this method may invalidate any existing indices for use with this collection.
- Parameter k: The number of elements to remove from the collection.
k
must be greater than or equal to zero and must not exceed the number of elements in the collection.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
mutating
func
removeFirst
(
_
k
:
Int
)
Removes the elements in the specified subrange from the collection.
All the elements following the specified position are moved to close the gap. This example removes three elements from the middle of an array of measurements.
var
measurements
= [
1.2
,
1.5
,
2.9
,
1.2
,
1.5
]
measurements
.
removeSubrange
(
1
..
<
4
)
(
measurements
)
// Prints "[1.2, 1.5]"
Calling this method may invalidate any existing indices for use with this collection.
- Parameter bounds: The range of the collection to be removed. The bounds of the range must be valid indices of the collection.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
mutating
func
removeSubrange
(
_
bounds
:
Range
<
Self
.
Index
>
)
Removes the elements in the specified subrange from the collection.
All the elements following the specified position are moved to close the gap. This example removes three elements from the middle of an array of measurements.
var
measurements
= [
1.2
,
1.5
,
2.9
,
1.2
,
1.5
]
measurements
.
removeSubrange
(
1
..
<
4
)
(
measurements
)
// Prints "[1.2, 1.5]"
Calling this method may invalidate any existing indices for use with this collection.
- Parameter bounds: The range of the collection to be removed. The bounds of the range must be valid indices of the collection.
Complexity: O(n), where n is the length of the collection.
Declaration
@
inlinable
public
mutating
func
removeSubrange
<
R
>
(
_
bounds
:
R
)
where
R
:
RangeExpression
,
Self
.
Index
==
R
.
Bound
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.
var
nums
= [
10
,
20
,
30
,
40
,
50
]
nums
.
replaceSubrange
(
1
...
3
,
with
:
repeatElement
(
1
,
count
:
5
))
(
nums
)
// Prints "[10, 1, 1, 1, 1, 1, 50]"
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.
Complexity: O(n + m), where n is length of this collection and m is the length of
newElements
. If the call to this method simply appends the contents ofnewElements
to the collection, the complexity is O(m).
Declaration
@
inlinable
public
mutating
func
replaceSubrange
<
C
,
R
>
(
_
subrange
:
R
,
with
newElements
:
C
)
where
C
:
Collection
,
R
:
RangeExpression
,
Self
.
Element
==
C
.
Element
,
Self
.
Index
==
R
.
Bound
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.
var
nums
= [
10
,
20
,
30
,
40
,
50
]
nums
.
replaceSubrange
(
1
...
3
,
with
:
repeatElement
(
1
,
count
:
5
))
(
nums
)
// Prints "[10, 1, 1, 1, 1, 1, 50]"
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.
Complexity: O(n + m), where n is length of the array and m is the length of
newElements
. If the call to this method simply appends the contents ofnewElements
to the array, this method is equivalent toappend(contentsOf:)
.
Declaration
@
inlinable
public
mutating
func
replaceSubrange
<
C
>
(
_
subrange
:
Range
<
Int
>
,
with
newElements
:
C
)
where
Element
==
C
.
Element
,
C
:
Collection
Prepares the collection to store the specified number of elements, when doing so is appropriate for the underlying type.
If you will be adding a known number of elements to a collection, use
this method to avoid multiple reallocations. A type that conforms to
RangeReplaceableCollection
can choose how to respond when this method
is called. Depending on the type, it may make sense to allocate more or
less storage than requested or to take no action at all.
- Parameter n: The requested number of elements to store.
Declaration
@
inlinable
public
mutating
func
reserveCapacity
(
_
n
:
Int
)
Reserves enough space to store the specified number of elements.
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 size of the newly allocated storage might be
greater than the requested capacity. Use the array's capacity
property
to determine the size of the new storage.
Preserving an Array's Geometric Growth Strategy
If you implement a custom data structure backed by an array that grows
dynamically, naively calling the reserveCapacity(_:)
method can lead
to worse than expected performance. Arrays need to follow a geometric
allocation pattern for appending elements to achieve amortized
constant-time performance. The Array
type's append(_:)
and
append(contentsOf:)
methods take care of this detail for you, but
reserveCapacity(_:)
allocates only as much space as you tell it to
(padded to a round value), and no more. This avoids over-allocation, but
can result in insertion not having amortized constant-time performance.
The following code declares values
, an array of integers, and the
addTenQuadratic()
function, which adds ten more values to the values
array on each call.
var
values
: [
Int
] = [
0
,
1
,
2
,
3
]
// Don't use 'reserveCapacity(_:)' like this
func
addTenQuadratic
() {
let
newCount
=
values
.
count
+
10
values
.
reserveCapacity
(
newCount
)
for
n
in
values
.
count
..
<
newCount
{
values
.
append
(
n
)
}
}
The call to reserveCapacity(_:)
increases the values
array's capacity
by exactly 10 elements on each pass through addTenQuadratic()
, which
is linear growth. Instead of having constant time when averaged over
many calls, the function may decay to performance that is linear in
values.count
. This is almost certainly not what you want.
In cases like this, the simplest fix is often to simply remove the call
to reserveCapacity(_:)
, and let the append(_:)
method grow the array
for you.
func
addTen
() {
let
newCount
=
values
.
count
+
10
for
n
in
values
.
count
..
<
newCount
{
values
.
append
(
n
)
}
}
If you need more control over the capacity of your array, implement your
own geometric growth strategy, passing the size you compute to
reserveCapacity(_:)
.
- Parameter minimumCapacity: The requested number of elements to store.
Complexity: O(n), where n is the number of elements in the array.
Declaration
@
inlinable
public
mutating
func
reserveCapacity
(
_
minimumCapacity
:
Int
)
Exchanges the values at the specified indices of the collection.
Both parameters must be valid indices of the collection that are not
equal to endIndex
. Calling swapAt(_:_:)
with the same index as both
i
and j
has no effect.
Complexity: O(1)
Declaration
@
inlinable
public
mutating
func
swapAt
(
_
i
:
Self
.
Index
,
_
j
:
Self
.
Index
)
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
@
inlinable
public
mutating
func
withContiguousMutableStorageIfAvailable
<
R
>
(
_
body
: (
inout
UnsafeMutableBufferPointer
<
Element
>
)
throws
-
>
R
)
rethrows
-
>
R
?
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
@
inlinable
public
mutating
func
withContiguousMutableStorageIfAvailable
<
R
>
(
_
body
: (
inout
UnsafeMutableBufferPointer
<
Self
.
Element
>
)
throws
-
>
R
)
rethrows
-
>
R
?
Call body(p)
, where p
is a pointer to the collection's
contiguous storage. If no such storage exists, it is
first created. If the collection does not support an internal
representation in a form of contiguous storage, body
is not
called and nil
is returned.
A Collection
that provides its own implementation of this method
must also guarantee that an equivalent buffer of its SubSequence
can be generated by advancing the pointer by the distance to the
slice's startIndex
.
Declaration
@
inlinable
public
func
withContiguousStorageIfAvailable
<
R
>
(
_
body
: (
UnsafeBufferPointer
<
Element
>
)
throws
-
>
R
)
rethrows
-
>
R
?
Calls a closure with a pointer to the array's contiguous storage.
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:
let
numbers
= [
1
,
2
,
3
,
4
,
5
]
let
sum
=
numbers
.
withUnsafeBufferPointer
{
buffer
-
>
Int
in
var
result
=
0
for
i
in
stride
(
from
:
buffer
.
startIndex
,
to
:
buffer
.
endIndex
,
by
:
2
) {
result
+=
buffer
[
i
]
}
return
result
}
// 'sum' == 9
The pointer passed as an argument to body
is valid only during the
execution of withUnsafeBufferPointer(_:)
. Do not store or return the
pointer for later use.
- Parameter body: A closure with an
UnsafeBufferPointer
parameter that points to the contiguous storage for the array. Ifbody
has a return value, that value is also used as the return value for thewithUnsafeBufferPointer(_:)
method. The pointer argument is valid only for the duration of the method's execution.
Declaration
@
inlinable
public
func
withUnsafeBufferPointer
<
R
>
(
_
body
: (
UnsafeBufferPointer
<
Element
>
)
throws
-
>
R
)
rethrows
-
>
R
Calls the given closure with a pointer to the underlying bytes of the array's contiguous storage.
The array's Element
type must be a trivial type, which can be copied
with just a bit-for-bit copy without any indirection or
reference-counting operations. Generally, native Swift types that do not
contain strong or weak references are trivial, as are imported C structs
and enums.
The following example copies the bytes of the numbers
array into a
buffer of UInt8
:
var
numbers
= [
1
,
2
,
3
]
var
byteBuffer
: [
UInt8
] = []
numbers
.
withUnsafeBytes
{
byteBuffer
.
append
(
contentsOf
: $
0
)
}
// byteBuffer == [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, ...]
- Parameter body: A closure with an
UnsafeRawBufferPointer
parameter that points to the contiguous storage for the array. If no such storage exists, it is created. Ifbody
has a return value, that value is also used as the return value for thewithUnsafeBytes(_:)
method. The argument is valid only for the duration of the closure's execution.
Declaration
@
inlinable
public
func
withUnsafeBytes
<
R
>
(
_
body
: (
UnsafeRawBufferPointer
)
throws
-
>
R
)
rethrows
-
>
R
Calls the given closure with a pointer to the array's mutable contiguous storage.
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 modifying the contents of the
UnsafeMutableBufferPointer
argument to body
alters the contents of
the array:
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
.
withUnsafeMutableBufferPointer
{
buffer
in
for
i
in
stride
(
from
:
buffer
.
startIndex
,
to
:
buffer
.
endIndex
-
1
,
by
:
2
) {
buffer
.
swapAt
(
i
,
i
+
1
)
}
}
(
numbers
)
// Prints "[2, 1, 4, 3, 5]"
The pointer passed as an argument to body
is valid only during the
execution of withUnsafeMutableBufferPointer(_:)
. Do not store or
return the pointer for later use.
Warning: Do not rely on anything about the array that is the target of this method during execution of the
body
closure; it might not appear to have its correct value. Instead, use only theUnsafeMutableBufferPointer
argument tobody
.
- Parameter body: A closure with an
UnsafeMutableBufferPointer
parameter that points to the contiguous storage for the array. Ifbody
has a return value, that value is also used as the return value for thewithUnsafeMutableBufferPointer(_:)
method. The pointer argument is valid only for the duration of the method's execution.
Declaration
@
inlinable
public
mutating
func
withUnsafeMutableBufferPointer
<
R
>
(
_
body
: (
inout
UnsafeMutableBufferPointer
<
Element
>
)
throws
-
>
R
)
rethrows
-
>
R
Calls the given closure with a pointer to the underlying bytes of the array's mutable contiguous storage.
The array's Element
type must be a trivial type, which can be copied
with just a bit-for-bit copy without any indirection or
reference-counting operations. Generally, native Swift types that do not
contain strong or weak references are trivial, as are imported C structs
and enums.
The following example copies bytes from the byteValues
array into
numbers
, an array of Int
:
The pointer passed as an argument to body
is valid only for the
lifetime of the closure. Do not escape it from the closure for later
use.
Warning: Do not rely on anything about the array that is the target of this method during execution of the
body
closure; it might not appear to have its correct value. Instead, use only theUnsafeMutableRawBufferPointer
argument tobody
.
- Parameter body: A closure with an
UnsafeMutableRawBufferPointer
parameter that points to the contiguous storage for the array. If no such storage exists, it is created. Ifbody
has a return value, that value is also used as the return value for thewithUnsafeMutableBytes(_:)
method. The argument is valid only for the duration of the closure's execution.
Declaration
@
inlinable
public
mutating
func
withUnsafeMutableBytes
<
R
>
(
_
body
: (
UnsafeMutableRawBufferPointer
)
throws
-
>
R
)
rethrows
-
>
R
Type Methods
Creates a new collection by concatenating the elements of a collection and a sequence.
The two arguments must have the same Element
type. For example, you can
concatenate the elements of an integer array and a Range<Int>
instance.
let
numbers
= [
1
,
2
,
3
,
4
]
let
moreNumbers
=
numbers
+
5
...
10
(
moreNumbers
)
// Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
The resulting collection has the type of the argument on the left-hand
side. In the example above, moreNumbers
has the same type as numbers
,
which is [Int]
.
Declaration
@
inlinable
public
static
func
+
<
Other
>
(
lhs
:
Self
,
rhs
:
Other
) -
>
Self
where
Other
:
Sequence
,
Self
.
Element
==
Other
.
Element
Creates a new collection by concatenating the elements of a sequence and a collection.
The two arguments must have the same Element
type. For example, you can
concatenate the elements of a Range<Int>
instance and an integer array.
let
numbers
= [
7
,
8
,
9
,
10
]
let
moreNumbers
=
1
...
6
+
numbers
(
moreNumbers
)
// Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
The resulting collection has the type of argument on the right-hand side.
In the example above, moreNumbers
has the same type as numbers
, which
is [Int]
.
Declaration
@
inlinable
public
static
func
+
<
Other
>
(
lhs
:
Other
,
rhs
:
Self
) -
>
Self
where
Other
:
Sequence
,
Self
.
Element
==
Other
.
Element
Creates a new collection by concatenating the elements of two collections.
The two arguments must have the same Element
type. For example, you can
concatenate the elements of two integer arrays.
let
lowerNumbers
= [
1
,
2
,
3
,
4
]
let
higherNumbers
:
ContiguousArray
= [
5
,
6
,
7
,
8
,
9
,
10
]
let
allNumbers
=
lowerNumbers
+
higherNumbers
(
allNumbers
)
// Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
The resulting collection has the type of the argument on the left-hand
side. In the example above, moreNumbers
has the same type as numbers
,
which is [Int]
.
Declaration
@
inlinable
public
static
func
+
<
Other
>
(
lhs
:
Self
,
rhs
:
Other
) -
>
Self
where
Other
:
RangeReplaceableCollection
,
Self
.
Element
==
Other
.
Element
Appends the elements of a sequence to a range-replaceable collection.
Use this operator to append the elements of a sequence to the end of
range-replaceable collection with same Element
type. This example
appends the elements of a Range<Int>
instance to an array of integers.
var
numbers
= [
1
,
2
,
3
,
4
,
5
]
numbers
+=
10
...
15
(
numbers
)
// Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
Complexity: O(m), where m is the length of the right-hand-side argument.
Declaration
@
inlinable
public
static
func
+=
<
Other
>
(
lhs
:
inout
Self
,
rhs
:
Other
)
where
Other
:
Sequence
,
Self
.
Element
==
Other
.
Element
The
ContiguousArray
type is a specialized array that always stores its elements in a contiguous region of memory. This contrasts withArray
, which can store its elements in either a contiguous region of memory or anNSArray
instance if itsElement
type is a class or@objc
protocol.If your array's
Element
type is a class or@objc
protocol and you do not need to bridge the array toNSArray
or pass the array to Objective-C APIs, usingContiguousArray
may be more efficient and have more predictable performance thanArray
. If the array'sElement
type is a struct or enumeration,Array
andContiguousArray
should have similar efficiency.For more information about using arrays, see
Array
andArraySlice
, with whichContiguousArray
shares most properties and methods.