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).
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 Swiftvar evenNumbers = [2, 4, 6, 8]print(evenNumbers)let integerArray = [Int](repeating: 6, count: 3)print(integerArray)var emptyArray: [String] = []print(emptyArray)emptyArray.append("John")emptyArray.append("Sarah")print(emptyArray)
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 Swiftvar 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 arrayevenNumbers[2] = 53print( "After modification, Value of third element is \(evenNumbers[2])")// Adding new element to the arrayevenNumbers.append(101)print(evenNumbers)// Inserting value after the 0th indexevenNumbers.insert(22, at: 1)print(evenNumbers)
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 Swiftvar numbers = [4, 5, 1, 23, 41] // an array of numbersprint("Number of items are \(numbers.count) ")// Iterating over an arrayfor number in numbers {print(number)}