An array is an ordered collection of values that share the same data type.
Arrays are used to store multiple items in a single variable, rather than declaring separate variables for each item.
In Swift, arrays are heavily optimized and can safely store only one specific type of element.
You can create an array by placing elements inside square brackets [], separated by commas.
var colors = ["Red", "Green", "Blue", "Yellow"] print(colors)
To create an empty array, you must explicitly specify the data type it will hold.
var emptyIntArray: [Int] = [] print(emptyIntArray)
You access an array element by referring to its index number inside square brackets.
In Swift, like most programming languages, array indexes start at 0.
var fruits = ["Apple", "Banana", "Orange"] print(fruits[0]) // Outputs "Apple"
If your array is assigned to a var, you can easily add, remove, or change elements.
You can change a specific item by accessing its index and assigning a new value.
You can add items to the end using the .append() method.
var numbers = [1, 2, 3] numbers[0] = 10 // Change the first element numbers.append(4) // Add to the end print(numbers) // Outputs [10, 2, 3, 4]
You can find out how many items are in an array using the .count property.
You can check if an array has no items using the .isEmpty boolean property.
What is the index of the first element in a Swift array?