Swift Arrays
An array is a single value that holds several values in a fixed order. Each stored value sits at a numbered position called an index.
Storing a list in one name
Square brackets hold the values in written order. Printing the name shows the whole group at once.
var scores = [10, 20, 30]
print(scores)Reading values by index
Index 0 picks the first stored value. A higher index picks a value further along the group.
let names = ["Ana", "Bo", "Cy"]
print(names[0])
print(names[2])Counting values and testing for empty
The two arrays here hold different numbers of values. Printing both tests for both arrays shows all four answers at once.
var full = [7, 8]
var empty: [Int] = []
print(full.count)
print(empty.count)
print(empty.isEmpty)
print(full.isEmpty)Replacing one stored value
An index on the left of = picks the slot to change. The rest of the group stays as it was.
var scores = [3, 6, 9]
scores[0] = 4
print(scores)
print(scores[0])Example
var temps = [18, 21, 19]
print(temps[0])
temps[2] = 22
print(temps)
print(temps.count)Key points
- One array name holds the whole group of values in order.
- Square brackets hold an array literal, with commas between the values.
- The type of an array that holds whole numbers is written [Int].
- Read one value by writing the name and an index in square brackets.
- Use .count on an array to count its stored values.
- Use .isEmpty on an array to test whether it holds any values.
- Writing a new value at an index replaces the value stored there.
In this example, the first line stores three numbers in temps. The second line prints the value at index 0, which is 18. The third line replaces the value at index 2 with 22. The fourth line prints the whole array as [18, 21, 22], and the last line prints its count as 3.
Note
The last index of an array is one less than its count.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
An array holds [5, 10, 15]. What does printing the value at index 1 give?