English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Arrays (Array)

In this tutorial, you will learn about arrays, how to create arrays, how to access the values of arrays, and some common operations in arrays.

In the previousSwift Data TypesIn the article, we learned how to create variables of certain data types that can store a single value/constants.

But what if we want to store multiple values of the same data type? In Swift, we use what is called Array things.

What is an array?

An array is just a container that can save multiple data of a data type in an ordered list, that is, you can get the elements in the order of the definition of each item in the array.

An array can store any type of data such as Int, String, Class, etc.

How to declare an array in Swift?

You can create an empty array by specifying the data type inside the brackets [].

Remember that you must include the type inside the brackets, otherwise Swift will treat it as a plain data type, and you can only store one value in it.

Example1: Declare an empty array

let emptyIntArr: [Int] = []
print(emptyIntArr)

When running the program, the output is:

[ ]

In the above program, we declared a constant emptyIntArr that can store an integer array and is initialized with 0 values.

or

You can also define an empty array as follows:

let emptyIntArr: Array<Int> = Array()
print(emptyIntArr)

or

Since Swift is a type inference language, you can also create an array without specifying the data type directly, but you must use some values for initialization so that the compiler can infer its type as:

Example2: Declare an array with certain values

let someIntArr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(someIntArr)

When running the program, the output is:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

In the above program, we declared a constant someIntArr that can store an Integer array without explicitly specifying the type. Additionally, we useValue 1,2,3,4,5,6,7,8,9 The array has been initialized.

Example3: Declare an array containing a specified number of single repeated values

You can also repeat a value a specified number of times to form an array in Swift. This is done by using the array initializer with repeating and count together.

let arrWithRepeatingValues = Array(repeating: "Hello, World", count: 4)
print(arrWithRepeatingValues)

When running the program, the output is:

["Hello, World", "Hello, World", "Hello, World", "Hello, World"]

In the above program, we defined a constant arrWithRepeatingValues, which stores strings Hello, World array,and repeat the same value4times, as specified in the example.

Note:In Swift, you cannot create an array of fixed length as you can in other programming languages. A fixed length array means that the array cannot contain more elements than you define during initialization.

How are values stored in an array?

Assuming you have a constant that can store a string array, as shown below:

let intArr = [21, 34, 54, 12]

The graphical representation of how values are stored in an array is as follows:

All arrays you create start from index 0. The first element is stored at index 0, the second element is stored at the next index (1) and so on.

How to access array elements in Swift?

You can use under: Use index syntax to access the element of the array, that is, you need to include the index of the value you want to access in the brackets after the array name.

Assuming you have declared an array intArr as described above. The first element is intArr[0], the second element is intArr[1], and so on.

Example4: Access the element of the array

let intArr = [21, 34, 54, 12]
print(intArr[0])
print(intArr[1]
print(intArr[2]
print(intArr[3]

When running the program, the output is:

21
34
54
12

You can also use for-in loop to access the elements of the array. For more information, please refer toSwift for-in loop.

How to modify in Swift/Add array element?

You can use index syntax and the assignment operator to modify the element of the array, that is, you need to include the index of the value you want to update in the brackets after the array name, followed by the assignment operator and the new value.

Example5: Modify the element of the array

var intArr = [21, 34, 54, 12]
intArr[0] = 12
intArr[1] = 42
intArr[2] = 45
intArr[3] = 21
print(intArr)

When running the program, the output is:

[12, 42, 45, 21]

You can also modify all elements of the array with the following new values, as shown below:

Example6: Modify the entire array

var intArr = [21, 34, 54, 12]
intArr = [1,2,3]
print(intArr)

When running the program, the output is:

[1, 2, 3]

However, to add a new element to an existing array, you cannot use index syntax. If you do so, it will eventually lead to an error. You cannot perform the following operation:

Example7: Use index syntax to add a new element to the array (invalid)

var intArr = [21, 34, 54, 12]
intArr[4] = 10

When running the program, the output is:

fatal error: Index out of range

The above program gives an error when assigning a new element to the array intArr. This is because intArr has not been indexed4Allocates additional memory and cannot store the given value.

To correctly insert a new element into an array, we use the array's append() method. The usage of append() will be introduced later.

Built-in functions and properties of the array

1. isEmpty property

This property determines whether an array is empty. If an array does not contain any values, it returns true, otherwise it returns false.

Example8:How does isEmpty work?

let intArr = [21, 34, 54, 12]
print(intArr.isEmpty)

When running the program, the output is:

false

2.first property

This property is used to access the first element of the array.

Example9:How does first work?

let intArr = [21, 34, 54, 12]
print(intArr.first)

When running the program, the output is:

Optional(21)

Similarly, you can also use the last property to access the last element of the array.

3.append function (Append)

The append function is used to insert at the end of the array./Append element.

Example10:How does append work?

var intArr = [21, 34, 54, 12]
intArr.append(32)
print(intArr)

When running the program, the output is:

[21, 34, 54, 12, 32]

You can also append the contents of one array to another as follows:

var firstArr = [1,2,3,4]
var secondArr = [5,6,7,8]
firstArr.append(contentsOf: secondArr)
print(firstArr)

When running the program, the output is:

[1, 2, 3, 4, 5, 6, 7, 8]

4.insert function (Insert)

This function is used to insert an element at a specific index in the array./Append element.

Example11:How does insert work?

var intArr = [21,34,54,12]
intArr.insert(22, at: 1)
print(intArr)

When running the program, the output is:

[21, 22, 34, 54, 12]

Similarly, you can also use removeproperty to delete the element at the specified index.

5.remove() function (Remove)

This function deletes and returns the value specified at the specified position in the array.

Example12:How does remove work?

var strArr = ["ab","bc","cd","de"]
let removedVal = strArr.remove(at: 1)
print("removed value is \(removedVal)")
print(strArr)

When running the program, the output is:

removed value is bc
["ab", "cd", "de"]

Similarly, you can also use removeFirst to delete the first element of the array, removeLast to delete the last element of the array, and removeAll to clear the array.

6.reversed() function (Reverse)

This function returns the elements of the array in reverse order.

Example13:How does reversed() work?

var intArr = [21,22,23,24]
let reversedArr = Array(intArr.reversed())
print(reversedArr)

When running the program, the output is:

[24, 23, 22, 21]

7.count property (Count)

This property returns the total number of elements in the array.

Example14:count Count

let floatArr = [10.2,21.3,32.0,41.3]
print(floatArr.count)

When running the program, the output is:

4

Precautions

When accessing array elements using subscript syntax in Swift, you must ensure that the value is at the index; otherwise, it will cause a runtime crash. Let's see an example:

let intArr = [21, 34, 54, 12]
print(intArr[-1]

When running the program, the output is:

fatal error: Index out of range

In the above program, the index -1 inNo value. Therefore, a runtime crash will occur when you try to access the value at the index.

To prevent this situation, first find the index of the element to be deleted. Then delete the element at the index, as shown below:

var intArr = [21, 34, 54, 12]
if let index = intArr.index(of: 34) {
    print("found index")
    let val = intArr.remove(at: index)
    print(val)
}

When running the program, the output is:

found index
34