Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are arrays in Swift?

Mohammad Razi ul Haq

Arrays are collections of same-type data values stored in contiguous memory locations. Arrays can hold values of any data type (e.g., strings, integers, floating-point numbers, etc.)

The values in an array, also called elements, can be accessed through an index (starts from zero).

An array with length 5. Index starts at 0.

How to create arrays in Swift

To create an array in Swift, surround a comma-separated list of values with square brackets (e.g., [1,2,3,4]). We can also initialize an array by giving the length of the array and the initial value of elements.

The code below shows all the ways we can initialize and declare an array in Swift:

import Swift

var evenNumbers = [2, 4, 6, 8]

let integerArray = [Int](repeating: 6, count: 3)

var emptyArray: [String] = []

The code shows three different ways of declaring arrays

How to access and modify contents of arrays

We can use indices to access specific items in an array. Arrays are zero-indexed, i.e., the first item will be indexed at zero. To modify the contents, we assign the new value to a particular index that we want to replace the value at. We can add elements to the array using the append function. We can also use the insert function to insert/append elements at specific indices of the array.

import Swift

var evenNumbers = [2, 4, 6]

var firstValue = evenNumbers[0]
print( "Value of first element is \(firstValue)" )
print( "Value of second element is \(evenNumbers[1])" )
print( "Value of third element is \(evenNumbers[2])" )

// Modifying the value of the third element in array
evenNumbers[2] = 53
print( "After modification, Value of third element is \(evenNumbers[2])")

// Adding new element to the array

// Inserting value after the 0th index
evenNumbers.insert(22, at: 1)
The code shows different ways of modifying and accessing arrays.

Arrays also have several other functions, such as the count function that returns the number of elements in the array. The enumerate function returns the index of an item along with its value. We also have to remember that index values cannot be negative or greater than the number of elements in an array.

import Swift

var numbers = [4, 5, 1, 23, 41] // an array of numbers
print("Number of items are \(numbers.count) ")

// Iterating over an array
for number in numbers {
Using the count function and iterating over the elements of an array




Mohammad Razi ul Haq

View all Courses

Keep Exploring