Menu
Coddy logo textTech

Accessing Elements

Part of the Fundamentals section of Coddy's Swift journey — lesson 63 of 86.

Now that you know how to create arrays, let's learn how to access individual elements within them. Each element in an array has a position called an index, and Swift uses zero-based indexing—meaning the first element is at index 0, not 1.

To access an element, use square brackets with the index number:

let fruits = ["Apple", "Banana", "Orange", "Mango"]
print(fruits[0])  // Apple
print(fruits[2])  // Orange

You can also access the first and last elements using built-in properties:

let numbers = [10, 20, 30, 40]
print(numbers.first!)  // 10
print(numbers.last!)   // 40

The count property tells you how many elements are in the array, which is useful when you need to access the last element by index:

let colors = ["Red", "Green", "Blue"]
print(colors.count)           // 3
print(colors[colors.count - 1])  // Blue

Be careful—accessing an index that doesn't exist will crash your program. If an array has 3 elements, valid indices are 0, 1, and 2.

challenge icon

Challenge

Easy

You are provided with the following array:

let cities = ["Tokyo", "Paris", "London", "Sydney", "Cairo"]

Using array indexing and properties, print the following information on separate lines:

  1. The first city (using index)
  2. The third city (using index)
  3. The last city (using the count property to calculate the index)
  4. The total number of cities in the array

Your output should be:

Tokyo
London
Cairo
5

Cheat sheet

Arrays use zero-based indexing, meaning the first element is at index 0. Access elements using square brackets with the index number:

let fruits = ["Apple", "Banana", "Orange", "Mango"]
print(fruits[0])  // Apple
print(fruits[2])  // Orange

Access the first and last elements using built-in properties:

let numbers = [10, 20, 30, 40]
print(numbers.first!)  // 10
print(numbers.last!)   // 40

Use the count property to get the number of elements in an array:

let colors = ["Red", "Green", "Blue"]
print(colors.count)              // 3
print(colors[colors.count - 1])  // Blue (last element by index)

Note: Accessing an index that doesn't exist will crash your program.

Try it yourself

let cities = ["Tokyo", "Paris", "London", "Sydney", "Cairo"]

// TODO: Write your code below
// 1. Print the first city (using index)

// 2. Print the third city (using index)

// 3. Print the last city (using the count property to calculate the index)

// 4. Print the total number of cities in the array
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals