Swift Arrays
An array (Array) stores multiple elements of the same type in order and is the most commonly used collection type in Swift.
It preserves insertion order, supports random access by index, and allows elements to be appended and removed dynamically.
This article covers creating arrays, subscript access, adding/deleting/modifying elements, three ways to iterate, and one of Swift arrays' most important features: value semantics and copy-on-write.
For key-value collections, see "Swift Dictionaries", and for unordered collections and higher-order functions, see "Sets and Higher-Order Functions》。
Creating an Array
An array type is written as the element type inside square brackets, such as [String] or [Int]; a literal lists its elements directly inside square brackets.
The brackets of the type and the literal look similar, but one is a type annotation and the other is a value.
Example
import Foundation
// Array literals; the element types are inferred by the compiler as [String] and [Int]
var sites
:
[
String
]
=
[
"Runoob"
,
"RUNOOB"
]
let numbers
=
[
1
,
2
,
3
]
// Empty arrays; the two forms are equivalent
var empty
:
[
Int
]
=
[
]
var empty2
=
[
Int
]
(
)
// Create an array of three zeros
let zeros
=
[
Int
]
(
repeating
:
0
, count
:
3
)
// Create an array from a range
let rangeArray
=
Array
(
1
...
5
)
(
sites, numbers, zeros, rangeArray, separator
:
" | "
)
(
empty.
count
, empty2.
isEmpty
)
The output of the above code is:
["Runoob", "RUNOOB"] | [1, 2, 3] | [0, 0, 0] | [1, 2, 3, 4, 5]
0 true
The common creation methods are compared below.
| Syntax | Description |
|---|---|
| [1, 2, 3] | Literal, with element type inferred by the compiler |
| var empty: [Int] = [] | Empty array with an explicit type annotation |
| Int | Call the type's initializer to get an empty array |
| [Int](repeating: 0, count: 3) | Created from a repeated value and a count |
| Array(1...5) | Created from a range or another sequence |
Note:The argument order of the repeating initializer is easy to get backwards: repeating comes first, andcount comes second. The form in older tutorials [Int](count:repeatedValue:) was replaced in Swift 3 and no longer compiles.
Accessing elements and subscripts
Elements are accessed by subscript; indices start at 0 and range from 0 to count - 1.
An out-of-range subscript triggers a runtime trap and terminates the program; it does not return nil like an optional.
For safe access, use first and last, which return optionals.
Example
import Foundation
let sites
=
[
"Runoob"
,
"RUNOOB"
,
"www.runoob.com"
]
(
sites
[
0
]
)
(
sites.
first
??
"Empty"
)
(
sites.
last
??
"Empty"
)
(
sites.
count
, sites.
isEmpty
)
(
sites.
firstIndex
(
of
:
"RUNOOB"
)
??
1
)
(
sites.
contains
(
"Runoob"
)
)
(
sites.
indices
.
contains
(
3
)
)
The output of the above code is:
Runoob
Runoob
www.runoob.com
3 false
1
true
false
indices is the range of valid subscripts for the array; checking with contains(_:) before accessing avoids an out-of-range crash.
In the example above the array has only three elements, so the valid indices are 0, 1, and 2; therefore indices.contains(3) is false.
Adding, deleting, and modifying
To modify an array it must first be declared with var; an array declared with let is immutable.
Use append to add, insert(_:at:) to insert, and remove(at:) and similar methods to delete.
Example
import Foundation
var sites
=
[
"Runoob"
,
"RUNOOB"
]
sites.
append
(
"www.runoob.com"
)
// Append to the end
sites.
insert
(
"Swift"
, at
:
0
)
// Insert at a specified position
sites
[
1
]
=
"RUNOOB tutorial"
// Modify a specified position
(
sites
)
let removed
=
sites.
remove
(
at
:
0
)
// Remove at a specified position and return the removed element
(
"Removed: (removed)"
)
sites.
removeLast
(
)
// Remove the last one
(
sites
)
The output of the above code is:
["Swift", "RUNOOB 教程", "RUNOOB", "www.runoob.com"]
删除:Swift
["RUNOOB 教程", "RUNOOB"]
Commonly used methods for adding, deleting, and modifying are summarized below.
| Method | Purpose | Return Value |
|---|---|---|
| append(_:) | Append an element at the end | None |
| insert(_:at:) | Insert an element at a specified index | None |
| remove(at:) | Remove the element at a specified index | The removed element |
| removeLast() | Remove the last element | The removed element |
| removeAll() | Empty the array | None |
append also has a batch version, append(contentsOf:), which appends an entire sequence at once.
Note that insert and remove shift subsequent elements, so frequent operations in the middle of a large array are costly.
Iterate over the array
Using for-in you can take out elements one by one; this is the most common form.
When you need the index, combine it with enumerated() to get an "(index + element)" tuple, or iterate over indices directly.
Example
import Foundation
let sites
=
[
"Runoob"
,
"RUNOOB"
,
"www.runoob.com"
]
// Only the elements
for
site in sites
{
(
site
)
}
// Need the index: enumerated() returns (offset, element)
for
(
index, site
)
in sites.
enumerated
(
)
{
(
"(index): (site)"
)
}
// Only the indices, then access by subscript
for
i in sites.
indices
{
(
"(i) -> (sites[i])"
)
}
The output of the above code is:
Runoob
RUNOOB
www.runoob.com
0: Runoob
1: RUNOOB
2: www.runoob.com
0 -> Runoob
1 -> RUNOOB
2 -> www.runoob.com
Note:enumerate() is the old Swift 2 spelling; since Swift 3 it has been renamed to enumerated(). Also, do not add or remove elements during iteration, as this makes the behavior unpredictable; when filtering or deleting, first use filter to generate a new array.
Value semantics and copy-on-write
Assigning an array to another variable or passing it as a function argument yields an independent copy.
Modifying one does not affect the other.
Example
import Foundation
var a
=
[
1
,
2
,
3
]
var b
=
a
// At this point a and b share storage; no real copy has been made yet
b.
append
(
4
)
// The copy occurs only when writing to b; a is unaffected
(
"a = (a), b = (b)"
)
The output of the above code is:
a = [1, 2, 3], b = [1, 2, 3, 4]
Swift does not copy the entire data at assignment; it first shares the same storage and merely increments the reference count.
Only when one party writes and finds that the storage is still shared does it make a real independent copy; this mechanism is calledcopy-on-write (Copy-On-Write, COW)。
It guarantees value semantics while avoiding repeated copying of large arrays when they are passed around, so neither performance nor semantics suffer.
For details of the mechanism, see "Swift Value Semantics and Copy-On-Write》。
Note:If a struct contains a nested reference type, value semantics are broken. Modifying the referenced object in a copy is visible in the original; such cases require you to implement a deep copy yourself.
Common questions
Here are the most common questions about using arrays.
Is an array a value type or a reference type?
It is a value type. Assignment is semantically equivalent to a copy, but is optimized by copy-on-write: a copy is made only when an actual write occurs.
This is completely different from NSArray in Objective-C, where the same object is shared.
What happens on an out-of-range subscript?
It triggers a runtime trap and terminates the program immediately; there is no silent nil return and no "return a default value when out of range" behavior.
If you are unsure whether an index is valid, first check with indices.contains(index), or use properties like first and last that return optionals.
How to remember the order of the repeating and count arguments
Remember "first say what value, then how many", that is, [Int](repeating: 0, count: 3).
Writing it backwards as [Int](count: 3, repeating: 0) causes a compile error, with the compiler reporting that no matching initializer exists.
How to quickly find an element's index
Use firstIndex(of:), which returns an Int? and is nil when the element does not exist.
If you only want to check existence, contains(_:) is more direct.