Swift Arrays

Swift Arrays

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.


Creating Arrays

You can create an array by placing elements inside square brackets [], separated by commas.

Creating an Array:

var colors = ["Red", "Green", "Blue", "Yellow"]
print(colors)

To create an empty array, you must explicitly specify the data type it will hold.

Empty Array:

var emptyIntArray: [Int] = []
print(emptyIntArray)

Accessing Elements

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.

Accessing Elements:

var fruits = ["Apple", "Banana", "Orange"]
print(fruits[0]) // Outputs "Apple"

Modifying Arrays

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.

Modifying an Array:

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]

Array Properties

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.


Exercise

What is the index of the first element in a Swift array?